[Java Foundation] -- Common methods for FileUtils tool classes

1. Introduction to FileUtils

File IO is the basic API that we often use in our daily projects. Common IO read and write operations base class byte streams InputStream and OutputStream, character stream Reader and Writer already cover common API functions in our daily project development. For a specific basic review, see a cdsn blog post: The difference between a character stream and a byte stream

        What I want to say today is that FileUtils, a better file manipulation tool class based on the above API encapsulated by the Apache open source project, covers static class encapsulation commonly used for reading files, copying files, copying directories and files, deleting directories and files, and clearing directories.

The use of FileUtils requires the introduction of FileUtils under apache's commons-io package, import: import org.apache.commons.io.FileUtils;

Official API documentation: http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html

Import dependencies are required for maven project use:

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>

Here is a brief introduction to the use of its common API methods.

1.1. Read files

The following are all static methods I feel I can use in the official API, such as readFileToString, readLines (read by line), and the corresponding static methods also provide support for encoded utf-8 format reading.

 

  1.2. Copy files

The commonly used API methods are as follows, such as copyFile, copyInputStreamToFile, and copyFileToDirectory.

  1 Copy files to files: copyFile(File srcFile, File destFile):

File file = new File("E:\\java\\file01\\abc Snow.jpg");
String destFilePath = "E:\\java\\file02";
String destFileName = "abc Snow 02.jpg";
try {
    FileUtils fileUtils = new FileUtils();
    //Date when the file was copied to a new location and saved.
    fileUtils.copyFile(file, new File(destFilePath,destFileName));
    System.out.println("File copied successfully");
} catch (IOException e) {
    e.printStackTrace();
    System.out.println(e.getMessage());
}

(2) Copy files to byte output stream: copyFile(File input, OutputStream output)

String destFileName = "abc Snow 03.jpg";
//From File copy to an Byte output stream.
FileUtils.copyFile(file, new FileOutputStream(new File(destFilePath,destFileName)));

(3) The date when the files were copied to the directory where they were saved: copyFileToDirectory(File srcFile, File destDir)

The file name of the copy cannot be customized, just like the original file name

//The date the file was copied to the directory where it was kept.
FileUtils.copyFileToDirectory(file, new File(destFilePath));

 

1.3. Copy directories and files

The main API s are as follows, which include the copy directory and subdirectories under the directory and the method of copying files:

 

  1 Copy the whole directory to the new location and keep the original file date: copyDirectory(File srcDir, File destDir)

      It contains files and subdirectory files and maintains the original file date

File file = new File("E:\\java\\file01");
String destFilePath = "E:\\java\\file03";
try {
    //Copy the entire directory to the new location and keep the original file date.
    FileUtils.copyDirectory(file, new File(destFilePath));
    System.out.println("File directory copied successfully");
} catch (IOException e) {
    e.printStackTrace();
    System.out.println(e.getMessage());
}

  (2) Copy the filtered directory to a new location:

copyDirectory(File srcDir, File destDir, FileFilter filter)

The file filter filters the copies of files containing files and subdirectories and maintains the original file date.

String destFilePath = "E:\\java\\file04";
//Copy the filtered directory and keep the original file date in a new location.
FileUtils.copyDirectory(file, new File(destFilePath), new FileFilter() {
    @Override
    public boolean accept(File pathname) {
        if(pathname.isDirectory()) return true;
        else {
            boolean b1 = pathname.getName().endsWith(".txt");
            boolean b2 = pathname.getName().endsWith(".jpg");
            return b1 || b2;
        }
    }
});

 

1.4. Delete directories and files

The main API deletion methods are as follows, commonly used are deleteDirectory, deleteQuietly, forceDelete, etc., which are mainly used for cascade deletion and forced deletion without causing exceptions. Very strong.

  Delete the specified file without throwing an exception: deleteQuietly(File file)

File file = new File("E:\\java\\file04\\abc Snow.jpg");
//Delete the specified file without throwing an exception.
FileUtils.deleteQuietly(file);

(2) Delete the specified file without throwing an exception: forceDelete(File file)

File file = new File("E:\\java\\file04\\abc Snow.jpg");
try {
    FileUtils.forceDelete(file);
    System.out.println("Operation Successful");
} catch (IOException e) {
    e.printStackTrace();
    System.out.println(e.getMessage());
}

(3) Delete directories recursively: deleteDirectory(File directory)

Delete its containing and subdirectory files

File file = new File("E:\\java\\file04\\abc Snow.jpg");
//Delete directories recursively.
try {
    FileUtils.deleteDirectory(new File(destFilePath));
    System.out.println("Operation Successful");
} catch (IOException e) {
    e.printStackTrace();
    System.out.println(e.getMessage());
}

1.5. Clear directory

The main API s are as follows, mainly used to clean up folders in the current directory (which will not be deleted to the current directory level) and the files they contain.

  Clear the files and subdirectory files under the directory without deleting the directory folder. There is no error in this directory:

String destFilePath = "E:\\java\\file04";
try {
    FileUtils.cleanDirectory(new File(destFilePath));
    System.out.println("Operation Successful");
} catch (IOException e) {
    e.printStackTrace();
    System.out.println(e.getMessage());
}

1.6. File Size Count Constant

(1) EMPTY_FILE_ARRAY, empty file array:

/**
   * An empty array of type {@code File}.
   */
public static final File[] EMPTY_FILE_ARRAY = {};

(2) 1GB size, corresponding to long type and BigInteger packaging type respectively:

/**
   * The number of bytes in a gigabyte.
   */
public static final long ONE_GB = ONE_KB * ONE_MB;

 /**
    * The number of bytes in a gigabyte.
    *
    * @since 2.4
    */
public static final BigInteger ONE_GB_BI = ONE_KB_BI.multiply(ONE_MB_BI);

(3) Similar display types of KB and MB:

/**
     * The number of bytes in a kilobyte.
     */
public static final long ONE_KB = 1024;

/**
   * The number of bytes in a kilobyte.
   *
   * @since 2.4
   */
public static final BigInteger ONE_KB_BI = BigInteger.valueOf(ONE_KB);

/**
   * The number of bytes in a megabyte.
   */
public static final long ONE_MB = ONE_KB * ONE_KB;

 

  Post to CSDN Blog:

Common methods for FileUtils tool classes

Based on the blogger's blog posts, I have made a small part of the knowledge supplement, and thank the blogger for providing a platform for blog posts to share learning knowledge.

Standing on the shoulders of giants, we can learn more ~

 

Posted by prem on Sun, 31 Oct 2021 10:42:22 -0700