FileUtil

Introduction

File operations are relatively complex in IO operations, but they are also the most frequently used part. Almost all of our projects have a utility class called FileUtil or FileUtils. I think Hutool should incorporate this utility class to solve most of the file operation problems.

Overall, the FileUtil class includes the following categories of operations:

  1. File operations: including creating, deleting, copying, moving, renaming, etc., of file directories
  2. File determination: determining whether a file or directory is non-empty, a directory, or a file, etc.
  3. Absolute path: converting files in ClassPath to absolute path files.
  4. File name: getting the main file name and extension
  5. Reading operations: including operations similar to IoUtil’s getReader and readXXX
  6. Writing operations: including getWriter and writeXXX operations

In FileUtil, I have tried to align the method names with Linux, for example, the method for creating a file is not createFile, but touch. This consistency greatly increases the learning speed for those familiar with Linux. Of course, if you are not familiar with Linux, the use of FileUtil is helping you learn Linux commands. These Linux-like methods include:

  • ls to list directories and files
  • touch to create a file and automatically create its parent directory if it does not exist
  • mkdir to create a directory and recursively create each level of directory
  • del to delete a file or directory (recursively deletes without checking whether it is empty), this method is equivalent to the Linux delete command
  • copy to copy a file or directory

These methods provide user-friendly operations. For example, the touch method creates a file and automatically creates its parent directory if required. Similarly, mkdir also creates parent directories.

It should be noted that the del method deletes directories without checking whether they are empty, which is convenient for use but may also result in some unforeseeable consequences (such as deleting directories that should not be deleted due to spelling mistakes). Therefore, please use this method carefully.

For more tool methods in FileUtil, please refer to the API documentation.