FileUtils Day Notes

 

 Recently, I was doing file-related operations and read the code of org.apache.commons.io.FileUtils. I would like to share my study process as follows:

 

1. Summary

pom dependencies:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
Package name: org.apache.commons.io
Class Name: FileUtils.java
 
2. Methods
1. public static File getFile(File directory, String... names)
Description: Get a file in the base directory, the directory and multiple names are combined into a path
example:
    @Test
    public void TestGetFile() {
        try {
            File file = FileUtils.getFile(new File("E:/data"), "gpslog", "msg.log");
            List<String> contents = FileUtils.readLines(file);

            for (String string : contents) {
                System.out.println(string);
            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 
2. public static File getFile(String... names)
Description: Get a file in the directory, and combine multiple names into one path
example:
    @Test
    public void TestGetFile() {
        try {
            File file = FileUtils.getFile("E:/data/gpslog", "msg.log");
            List<String> contents = FileUtils.readLines(file);

            for (String string : contents) {
                System.out.println(string);
            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 
3. public static String getTempDirectoryPath()
Description: Get the default temporary file path
example:
    @Test
    public void TestGetTempDirectoryPath() {
        try {
            String directoryPath = FileUtils.getTempDirectoryPath();

            System.out.println(directoryPath);
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 
4. public static File getTempDirectory()
Description: Get the folder object corresponding to the default temporary file path
example:
    @Test
    public void TestGetTempDirectory() {
        try {
            File directoryPathFile = FileUtils.getTempDirectory();
            if (directoryPathFile.isDirectory()) {
                String[] childs = directoryPathFile.list();
                for (String child : childs) {
                    System.out.println(child);
                }
            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 
5. public static String getUserDirectoryPath()
Description: Get the user directory file path
example:
    @Test
    public void TestGetUserDirectoryPath() {
        try {
            String userDirectoryPath = FileUtils.getUserDirectoryPath();
            System.out.println(userDirectoryPath);
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 
6. public static String getUserDirectoryPath()
Description: Get the user directory file path
example:
    @Test
    public void TestGetUserDirectory() {
        try {
            File directoryPathFile = FileUtils.getUserDirectory();
            if (directoryPathFile.isDirectory()) {
                String[] childs = directoryPathFile.list();
                for (String child : childs) {
                    System.out.println(child);
                }
            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 
  7. public static FileInputStream openInputStream(File file) throws IOException
Description: Get the input stream corresponding to the file
example:
    @Test
    public void TesTopenInputStream() {
        try {
            FileInputStream openInputStream = FileUtils.openInputStream(new File("E:/data/gpslog/msg.log"));
            byte[] data = new byte[openInputStream.available()];

            while (openInputStream.read(data) != -1) {
                System.out.println(new String(data));
            }

        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 
8. public static FileInputStream openInputStream(File file) throws IOException
Description: Get the output stream corresponding to the file. Each time the method is executed, it is not to append content, but to overwrite.
example:
    @Test
    public void TestOpenOutputStream() {
        try {
            FileOutputStream openOutputStream = FileUtils.openOutputStream(new File("E:/data/gpslog/msg.log"));
            openOutputStream.write("hello world2".getBytes());
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 
9. public static FileOutputStream openOutputStream(File file, boolean append) throws IOException
Description: Get the output stream corresponding to the file. When append is true, it means appending the content, otherwise it means overwriting the file content.
example:
    @Test
    public void TestOpenOutputStream() {
        try {
            FileOutputStream openOutputStream = FileUtils.openOutputStream(new File("E:/data/gpslog/msg.log"), true);
            openOutputStream.write("hello girl".getBytes());
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 
10. public static String byteCountToDisplaySize(long size)
Description: Get the file size conversion value corresponding to size, the minimum unit is byte. Units include: bytes, KB, MB, GB, TB, PB, EB
example:
    @Test
    public void TestByteCountToDisplaySize() {
        try {
            String byteCountToDisplaySize = FileUtils.byteCountToDisplaySize(1024 * 1024 * 1024);
            System.out.println("size=" + byteCountToDisplaySize);
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
  Output: size=1 GB
 
 
11. public static String byteCountToDisplaySize(BigInteger size)
Description: Get the file size conversion value corresponding to size, the minimum unit is byte. Units include: bytes, KB, MB, GB, TB, PB, EB
 
12. public static void touch(File file) throws IOException
Description: The last update time of the modified file. If the file exists, the last update time of the modified file is the current time; if it does not exist, the last update time of the file created and modified is the current time.
example:
    @Test
    public void TestTouch() {
        try {
            FileUtils.touch(new File("E:/data/gpslog/msg.log"));
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 
13. public static File[] convertFileCollectionToFileArray(Collection<File> files)
Description: Convert a collection of files to an array of files
example:
    @Test
    public void TestConvertFileCollectionToFileArray() {
        try {
            List<File> files = Lists.newArrayList(
                    new File("E:/data/gpslog/msg.log"),
                    new File("E:/data/gpslog/msg_null.log"));
            File[] convertFiles = FileUtils.convertFileCollectionToFileArray(files);
            for (File file : convertFiles) {
                System.out.println(file.getName() + " --> " + FileUtils.readFileToString(file));
            }

        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 
14. public static Collection<File> listFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)
Description: According to the file filter and folder filter, traverse the files in the directory that meet the filter conditions. The parameter description is as follows:
a. The first parameter indicates the folder to be traversed, and it is not allowed to be empty.
b. The second parameter indicates the filter conditions that the files under the folder need to meet, and are not allowed to be empty. There are many filters, such as EmptyFileFilter, NameFileFilter, PrefixFileFilter, etc.
c. The third parameter generally indicates whether to recursively traverse the folder. Empty means no recursive traversal, DirectoryFileFilter.INSTANCE means recursive traversal of folders.
 
example:
    @Test
    public void TestListFiles() {
        try {
            File directory = new File("E:/data/gpslog");
            IOFileFilter fileFilter = FileFilterUtils.and(EmptyFileFilter.NOT_EMPTY,
                    FileFilterUtils.suffixFileFilter("log"));

            List<File> found = (List<File>) FileUtils.listFiles(directory, fileFilter, DirectoryFileFilter.INSTANCE);
            for (File file : found) {
                System.out.println(file.getAbsolutePath());
            }

        } catch (Exception e) {
            e.printStackTrace ();
        }
    }

 
15. public static Collection<File> listFilesAndDirs( File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)
Description: According to the file filter and folder filter, traverse the files and folders in the directory that meet the filter conditions. The parameter description is as follows:
a. The first parameter indicates the folder to be traversed, and it is not allowed to be empty.
b. The second parameter indicates the filter conditions that the files under the folder need to meet, and are not allowed to be empty. There are many filters, such as EmptyFileFilter, NameFileFilter, PrefixFileFilter, etc.
c. The third parameter generally indicates whether to recursively traverse the folder. Empty means no recursive traversal, DirectoryFileFilter.INSTANCE means recursive traversal of folders.
example:
    @Test
    public void TestListFilesAndDirs() {
        try {
            File directory = new File("E:/data/gpslog");
            IOFileFilter fileFilter = FileFilterUtils.and(EmptyFileFilter.NOT_EMPTY,
                    FileFilterUtils.suffixFileFilter("log"));

            List<File> found = (List<File>) FileUtils.listFilesAndDirs(directory, fileFilter,
                    DirectoryFileFilter.INSTANCE);
            for (File file : found) {
                if (file.isDirectory()) {
                    System.out.println("Folder: " + file.getAbsolutePath());
                } else {
                    System.out.println("文件##" + file.getAbsolutePath());
                }
            }

        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
  output:
Folder: E:\data\gpslog
file##E:\data\gpslog\msg_null.log

 

16. public static Collection<File> listFiles(File directory, String[] extensions, boolean recursive)
Description: Filter the extended array according to the file name, and traverse the eligible files in the directory. The parameter description is as follows:
a. The first parameter indicates the folder to be traversed, and it is not allowed to be empty.
b. The second parameter represents the file name filter extension data.
c. The third parameter: true means recursive, false means non-recursive.
example:
    @Test
    public void TestListFiles2() {
        try {
            File directory = new File("E:/data/gpslog");
            List<File> found = (List<File>) FileUtils.listFiles(directory, new String[] { "log", "msg", "2" }, true);
            for (File file : found) {
                if (file.isDirectory()) {
                    System.out.println("Folder: " + file.getAbsolutePath());
                } else {
                    System.out.println("##文件##:" + file.getAbsolutePath());
                }
            }

        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 
17. public static boolean contentEquals(File file1, File file2) throws IOException
Description: Compare the contents of two files to determine if they are equal.
example:
    @Test
    public void TestContentEquals() {
        try {
            boolean eq = FileUtils.contentEquals(FileUtils.getFile("E:\\data\\gpslog\\msg_null.log"),
                    FileUtils.getFile("E:\\data\\gpslog\\msg_null.log"));
            System.out.println(eq);
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 
18. public static boolean contentEqualsIgnoreEOL(File file1, File file2, String charsetName) throws IOException
Description: Compare the contents of two files according to encoding to determine if they are equal.
example:
    @Test
    public void TestContentEqualsIgnoreEOL() {
        try {
            boolean eq = FileUtils.contentEqualsIgnoreEOL(FileUtils.getFile("E:\\data\\gpslog\\msg_null.log"),
                    FileUtils.getFile("E:\\data\\gpslog\\msg_null.log"), "UTF-8");
            System.out.println(eq);
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 
19. public static File toFile(URL url)
Description: Read the URL file path of the file protocol as a file
example:
    @Test
    public void TestToFile() {
        try {
            File urlFile = FileUtils.toFile(new URL("file:///E:/data/gpslog/msg_null.log"));

            System.out.println(FileUtils.readFileToString(urlFile));
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 
20. public static URL[] toURLs(File[] files) throws IOException
Description: Generate the corresponding URL array based on the file array
example:
    @Test
    public void TestToFile() {
        try {
            File[] files = new File[] { FileUtils.getFile("E:/data/gpslog/msg_null.log") };

            URL[] urls = FileUtils.toURLs(files);
            for (URL url : urls) {
                System.out.println(url.toString());
            }

        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 Output: file:/E:/data/gpslog/msg_null.log
 
21. public static void copyFileToDirectory(File srcFile, File destDir) throws IOException
Description: Copy the file to the target directory
example:
    @Test
    public void TestCopyFileToDirectory() {
        try {
            FileUtils.copyFileToDirectory(FileUtils.getFile("E:/data/gpslog/msg_null.log"),
                    FileUtils.getFile("E:/data/gpslog2"));
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326352566&siteId=291194637