7hutool actual FileUtil file tool class (common operation methods for more than 100 files)

Posted by tranzparency on Sun, 20 Feb 2022 03:50:08 +0100

If you are Xiaobai, this set of information can help you become a big bull. If you have rich development experience, this set of information can help you break through the bottleneck
2022web full set of video tutorial front-end architecture H5 vue node applet Video + data + code + interview questions.

Technical work should be rewarded
 follow+Click three times (like, comment, collect) and watch again to form a good habit

hutool actual combat (take you to master various tools inside) directory

Purpose: File tool class (common operation of files)

Usage scenario

Provide common operation methods for more than 100 files, including but not limited to: judge whether the file or folder is empty, judge whether the file is a file or folder, recurse all files in the folder, obtain all file names of the specified folder, obtain the content or path of the temporary folder or temporary file, calculate the total size of the folder or file, create a file or folder Create temporary file or temporary folder, delete file or folder, modify file name or folder name, copy file or folder, move file or folder, empty folder, obtain the absolute path of specification, compare two files, judge whether the file has been changed, obtain parent path or child path, obtain main file name or suffix, etc

Project reference

The basis of this blog post: hutool-5.6.5 version source code

        <dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-core</artifactId>
			<version>5.6.5</version>
		</dependency>

Method summary

method

describe

cn.hutool.core.io.FileUtil.isWindows()

Is it a Windows environment

cn.hutool.core.io.FileUtil.ls(java.lang.String)

List catalog files
The given absolute path cannot be a path in a compressed package

cn.hutool.core.io.FileUtil.isEmpty(java.io.File)

Is the file empty
Directory: empty when there is no file in it. File: empty when the file size is 0

cn.hutool.core.io.FileUtil.isNotEmpty(java.io.File)

Is the file not empty
Directory: empty when there is no file in it. File: empty when the file size is 0

cn.hutool.core.io.FileUtil.isDirEmpty(java.io.File)

Is the directory empty

cn.hutool.core.io.FileUtil.loopFiles(java.lang.String, java.io.FileFilter)

Recursively traverse all files in the directory and subdirectories
If the file provided is a file, the filtering result is returned directly

cn.hutool.core.io.FileUtil.loopFiles(java.io.File, java.io.FileFilter)

Recursively traverse all files in the directory and subdirectories
If the file provided is a file, the filtering result is returned directly

cn.hutool.core.io.FileUtil.walkFiles(java.io.File, java.util.function.Consumer)

Recursively traverse the directory and process the files under the directory. You can process the directory or files:

  • If it is not a directory, it will directly call {@ link Consumer} for processing
  • This method is called recursively for directory processing

cn.hutool.core.io.FileUtil.loopFiles(java.io.File, int, java.io.FileFilter)

Recursively traverse all files in the directory and subdirectories
If the file provided is a file, the filtering result is returned directly

cn.hutool.core.io.FileUtil.loopFiles(java.lang.String)

Recursively traverse all files in the directory and subdirectories

cn.hutool.core.io.FileUtil.loopFiles(java.io.File)

Recursively traverse all files in the directory and subdirectories

cn.hutool.core.io.FileUtil.listFileNames(java.lang.String)

Get all file names in the specified directory
Subdirectories will not be scanned

cn.hutool.core.io.FileUtil.newFile(java.lang.String)

Creating a File object is equivalent to calling new File() without any processing

cn.hutool.core.io.FileUtil.file(java.lang.String)

Create a File object and automatically identify the relative or absolute path. The relative path will be automatically found under ClassPath

cn.hutool.core.io.FileUtil.file(java.lang.String, java.lang.String)

Create File object
This method will check the slip vulnerability. See for the vulnerability description http://blog.nsfocus.net/zip-slip-2/

cn.hutool.core.io.FileUtil.file(java.io.File, java.lang.String)

Create File object
According to the path construction file, it can be built directly under Win and built separately under Linux. This method will check the slip vulnerability. See the vulnerability description http://blog.nsfocus.net/zip-slip-2/

cn.hutool.core.io.FileUtil.file(java.io.File, java.lang.String[])

Create files with multi-level directory parameters
This method will check the slip vulnerability. See for the vulnerability description http://blog.nsfocus.net/zip-slip-2/

cn.hutool.core.io.FileUtil.file(java.lang.String[])

Create files from multiple directories

Element name (multi-level directory name)

cn.hutool.core.io.FileUtil.file(java.net.URI)

Create File object

cn.hutool.core.io.FileUtil.file(java.net.URL)

Create File object

cn.hutool.core.io.FileUtil.getTmpDirPath()

Get temporary file path (absolute path)

cn.hutool.core.io.FileUtil.getTmpDir()

Get temporary file directory

cn.hutool.core.io.FileUtil.getUserHomePath()

Get user path (absolute path)

cn.hutool.core.io.FileUtil.getUserHomeDir()

Get user directory

cn.hutool.core.io.FileUtil.exist(java.lang.String)

Judge whether the file exists. If the path is null, false will be returned

cn.hutool.core.io.FileUtil.exist(java.io.File)

Judge whether the file exists. If the file is null, false will be returned

cn.hutool.core.io.FileUtil.exist(java.lang.String, java.lang.String)

Is there a matching file

cn.hutool.core.io.FileUtil.lastModifiedTime(java.io.File)

Specifies when the file was last modified

cn.hutool.core.io.FileUtil.lastModifiedTime(java.lang.String)

Specifies when the path file was last modified

cn.hutool.core.io.FileUtil.size(java.io.File)

Calculate the total size of a directory or file
When the given object is a file, directly call {@ link File#length()}
When the given object is a directory, traverse all files and directories under the directory, recursively calculate its size, and return the sum

cn.hutool.core.io.FileUtil.newerThan(java.io.File, java.io.File)

Is the last modification time of the given file or directory later than the given time

cn.hutool.core.io.FileUtil.newerThan(java.io.File, long)

Is the last modification time of the given file or directory later than the given time

cn.hutool.core.io.FileUtil.touch(java.lang.String)

Create a file and its parent directory. If the file exists, return the file directly
This method does not judge the type of File object. If File does not exist, its type cannot be judged

cn.hutool.core.io.FileUtil.touch(java.io.File)

Create a file and its parent directory. If the file exists, return the file directly
This method does not judge the type of File object. If File does not exist, its type cannot be judged

cn.hutool.core.io.FileUtil.touch(java.io.File, java.lang.String)

Create a file and its parent directory. If the file exists, return the file directly
The File type cannot be determined if the File method does not exist

cn.hutool.core.io.FileUtil.touch(java.lang.String, java.lang.String)

Create a file and its parent directory. If the file exists, return the file directly
This method does not judge the type of File object. If File does not exist, its type cannot be judged

cn.hutool.core.io.FileUtil.mkParentDirs(java.io.File)

Creates the parent directory of the given file or directory

cn.hutool.core.io.FileUtil.mkParentDirs(java.lang.String)

Create a parent folder and return to this folder directly if it exists

cn.hutool.core.io.FileUtil.del(java.lang.String)

Delete files or folders
If the path is relative, it will be converted to ClassPath path path! Note: when deleting a folder, you will not judge whether the folder is empty. If it is not empty, you will recursively delete sub files or folders
A file deletion failure will terminate the deletion operation

cn.hutool.core.io.FileUtil.del(java.io.File)

Delete files or folders
Note: when deleting a folder, you will not judge whether the folder is empty. If it is not empty, you will recursively delete sub files or folders
A file deletion failure will terminate the deletion operation

cn.hutool.core.io.FileUtil.clean(java.lang.String)

Empty Folder
Note: when emptying a folder, you will not judge whether the folder is empty. If it is not empty, you will recursively delete sub files or folders
A file deletion failure will terminate the deletion operation

cn.hutool.core.io.FileUtil.clean(java.io.File)

Empty Folder
Note: when emptying a folder, you will not judge whether the folder is empty. If it is not empty, you will recursively delete sub files or folders
A file deletion failure will terminate the deletion operation

cn.hutool.core.io.FileUtil.cleanEmpty(java.io.File)

Clean up empty folders
This method is used to recursively delete empty folders without deleting files
If the incoming folder itself is empty, delete it

cn.hutool.core.io.FileUtil.mkdir(java.lang.String)

Create a folder and return to it directly if it exists
This method does not judge the type of File object. If File does not exist, its type cannot be judged

cn.hutool.core.io.FileUtil.mkdir(java.io.File)

When you create a folder, you will recursively and automatically create its nonexistent parent folder. If it does exist, you will directly return to this folder
This method does not judge the type of File object. If File does not exist, its type cannot be judged

cn.hutool.core.io.FileUtil.createTempFile(java.io.File)

Create temporary file
The created file name is prefix [random] tmp

cn.hutool.core.io.FileUtil.createTempFile(java.io.File, boolean)

Create temporary file
The created file name is prefix [random] tmp

cn.hutool.core.io.FileUtil.createTempFile(java.lang.String, java.lang.String, java.io.File, boolean)

Create temporary file
The created file name is prefix [random] suffix From com. jodd. io. FileUtil

cn.hutool.core.io.FileUtil.copyFile(java.lang.String, java.lang.String, java.nio.file.StandardCopyOption[])

Copy files through the Files#copy(Path, Path, CopyOption...) method of JDK7 +

cn.hutool.core.io.FileUtil.copyFile(java.io.File, java.io.File, java.nio.file.StandardCopyOption[])

Copy files through the Files#copy(Path, Path, CopyOption...) method of JDK7 +

cn.hutool.core.io.FileUtil.copy(java.lang.String, java.lang.String, boolean)

Copy files or directories
If the destination file is a directory, copy the source file to the destination directory with the same file name

cn.hutool.core.io.FileUtil.copy(java.io.File, java.io.File, boolean)

Copy files or directories
The situation is as follows:

1. If both src and dest are directories, copy the src directory and all file directories under the src directory to dest. 2. src and dest are files and copy directly. The name is dest 3. src is a file and dest is a directory. Copy src to dest directory

cn.hutool.core.io.FileUtil.copyContent(java.io.File, java.io.File, boolean)

Copy files or directories
The situation is as follows:

1. If both src and dest are directories, copy all file directories under src to dest. 2. src and dest are files and copy directly. The name is dest. 3. src is a file and dest is a directory. Copy src to dest directory

cn.hutool.core.io.FileUtil.copyFilesFromDir(java.io.File, java.io.File, boolean)

Copy files or directories
The situation is as follows:

1. src and dest are directories, so all files (including subdirectories) under src are copied to dest. 2. src and dest are files and copied directly. The name is dest 3. src is a file and dest is a directory. Copy src to dest directory

cn.hutool.core.io.FileUtil.move(java.io.File, java.io.File, boolean)

Move files or directories

cn.hutool.core.io.FileUtil.rename(java.io.File, java.lang.String, boolean)

Modify the file name of a file or directory without changing the path, but simply modify the file name without retaining the extension.

FileUtil.rename(file, "aaa.png", true) xx/xx.png =>xx/aaa.png

cn.hutool.core.io.FileUtil.rename(java.io.File, java.lang.String, boolean, boolean)

Modify the file name of a file or directory without changing the path, but simply modify the file name
There are two modes of renaming:
1. When isRetainExt is true, keep the original extension:

FileUtil.rename(file, "aaa", true) xx/xx.png =>xx/aaa.png

2. When isRetainExt is false, the original extension is not retained and needs to be in newName

FileUtil.rename(file, "aaa.jpg", false) xx/xx.png =>xx/aaa.jpg

cn.hutool.core.io.FileUtil.getCanonicalPath(java.io.File)

Gets the absolute path of the specification

cn.hutool.core.io.FileUtil.getAbsolutePath(java.lang.String, java.lang.Class)

Get absolute path
This method does not determine whether the given path is valid (file or directory exists)

cn.hutool.core.io.FileUtil.getAbsolutePath(java.lang.String)

Gets the absolute path, relative to the directory of ClassPath
If the given is an absolute path, the original path is returned, and the original path replaces all with/
Compatible with Spring style path representation, for example: classpath: config / example Setting will also be converted after being recognized

cn.hutool.core.io.FileUtil.getAbsolutePath(java.io.File)

Get standard absolute path

cn.hutool.core.io.FileUtil.isAbsolutePath(java.lang.String)

The given path is already an absolute path
This method does not standardize the path. It is recommended to execute the {@ link #normalize(String)} method to standardize the path before judgment

cn.hutool.core.io.FileUtil.isDirectory(java.lang.String)

Judge whether it is a directory. If the path is null, false will be returned

cn.hutool.core.io.FileUtil.isDirectory(java.io.File)

Judge whether it is a directory. If file is null, false will be returned

cn.hutool.core.io.FileUtil.isFile(java.lang.String)

Judge whether it is a file. If the path is null, false will be returned

cn.hutool.core.io.FileUtil.isFile(java.io.File)

Judge whether it is a file. If the file is null, false will be returned

cn.hutool.core.io.FileUtil.equals(java.io.File, java.io.File)

Check whether the two files are the same file
The same File refers to whether the File object points to the same File or folder

cn.hutool.core.io.FileUtil.contentEquals(java.io.File, java.io.File)

Compare whether the contents of the two files are the same
First compare the length, and then compare the content if the length is consistent
This method is from Apache Commons io

cn.hutool.core.io.FileUtil.contentEqualsIgnoreEOL(java.io.File, java.io.File, java.nio.charset.Charset)

Compare whether the contents of the two files are the same
First, compare the length, and then compare the content. The comparison content is read by line, and each line is compared
This method is from Apache Commons io

cn.hutool.core.io.FileUtil.pathEquals(java.io.File, java.io.File)

Are the file paths the same
Compare the absolute paths of the two files, ignoring case in Windows and not in Linux.

cn.hutool.core.io.FileUtil.lastIndexOfSeparator(java.lang.String)

Gets the location of the last file path separator

cn.hutool.core.io.FileUtil.isModifed(java.io.File, long)

Determine whether the file has been changed
If the file object is null or the file does not exist, it is regarded as a change

cn.hutool.core.io.FileUtil.normalize(java.lang.String)

Repair path
If there is a separator at the end of the original path, it will be retained as the standard separator (/), otherwise it will not be retained

  1. 1. Unified use/
  2. 2. Multiple / convert to one/
  3. 3. Remove the spaces on both sides
  4. 4. And Convert to absolute path. When... Is more than the existing path, it will directly return to the root path

Chestnuts:

"/foo//" => "/foo/" "/foo/./" => "/foo/" "/foo/.../bar" => "/bar" "/foo/.../bar/" => "/bar/" "/foo/.../bar/.../baz" => "/baz" "/.../" => "/" "foo/bar/..." => "foo" "foo/.../bar" => "bar" "foo/.../.../bar" => "bar" "//server/foo/.../bar" => "/server/bar" "//server/.../bar" => "/bar" "C: oo...ar" => "C:/bar" "C:...ar" => "C:/bar" "~/foo/.../bar/" => "~/bar/" "~/.../bar" => "bar"

cn.hutool.core.io.FileUtil.subPath(java.lang.String, java.io.File)

Get relative subpath

Chestnuts:

dirPath: d:/aaa/bbb filePath: d:/aaa/bbb/ccc => ccc dirPath: d:/Aaa/bbb filePath: d:/aaa/bbb/ccc.txt => ccc.txt

cn.hutool.core.io.FileUtil.subPath(java.lang.String, java.lang.String)

Get relative subpath, ignoring case

Chestnuts:

dirPath: d:/aaa/bbb filePath: d:/aaa/bbb/ccc => ccc dirPath: d:/Aaa/bbb filePath: d:/aaa/bbb/ccc.txt => ccc.txt dirPath: d:/Aaa/bbb filePath: d:/aaa/bbb/ => ""

cn.hutool.core.io.FileUtil.pathEndsWith(java.io.File, java.lang.String)

Judge whether the file path has a specified suffix, ignoring case
Common phrase judgment extension

cn.hutool.core.io.FileUtil.getType(java.io.File)

Obtain the file type according to the header information of the file stream

  1,Unrecognized type is recognized by extension by default      2, xls,doc,msi Header information cannot be distinguished according to extension      3, zip May be docx,xlsx,pptx,jar,war Header information cannot be distinguished according to extension 

cn.hutool.core.io.FileUtil.convertCharset(java.io.File, java.nio.charset.Charset, java.nio.charset.Charset)

Convert file code
This method is used to convert the file code. The actual code of the read file must be consistent with the specified srcCharset code, otherwise it will cause garbled code

cn.hutool.core.io.FileUtil.convertLineSeparator(java.io.File, java.nio.charset.Charset, cn.hutool.core.io.file.LineSeparator)

Convert line breaks
Converts the newline character of the given file to the specified newline character

cn.hutool.core.io.FileUtil.cleanInvalid(java.lang.String)

Clear the illegal characters in the file name that are not supported under Windows, including: /: * "< >

cn.hutool.core.io.FileUtil.containsInvalid(java.lang.String)

Whether the file name contains illegal characters that are not supported under Windows, including: /: * "< >

cn.hutool.core.io.FileUtil.checksumCRC32(java.io.File)

Calculation file CRC32 check code

cn.hutool.core.io.FileUtil.checksum(java.io.File, java.util.zip.Checksum)

Calculation file check code

cn.hutool.core.io.FileUtil.getWebRoot()

Get the web root path under the Web project
The principle is to obtain the ClassPath path first. Since the ClassPath is located under WEB-INF/classes / in the web project, you can obtain two-level directories upward.

cn.hutool.core.io.FileUtil.getParent(java.lang.String, int)

Gets the parent path of the specified hierarchy

getParent("d:/aaa/bbb/cc/ddd", 0) -> "d:/aaa/bbb/cc/ddd" getParent("d:/aaa/bbb/cc/ddd", 2) -> "d:/aaa/bbb" getParent("d:/aaa/bbb/cc/ddd", 4) -> "d:/" getParent("d:/aaa/bbb/cc/ddd", 5) -> null

cn.hutool.core.io.FileUtil.getParent(java.io.File, int)

Gets the parent path of the specified hierarchy

getParent(file("d:/aaa/bbb/cc/ddd", 0)) -> "d:/aaa/bbb/cc/ddd" getParent(file("d:/aaa/bbb/cc/ddd", 2)) -> "d:/aaa/bbb" getParent(file("d:/aaa/bbb/cc/ddd", 4)) -> "d:/" getParent(file("d:/aaa/bbb/cc/ddd", 5)) -> null

cn.hutool.core.io.FileUtil.checkSlip(java.io.File, java.io.File)

Check whether the parent full path is the first half of the self path. If not, it indicates that it is not a child path, and there may be slip injection.

see http://blog.nsfocus.net/zip-slip-2/

cn.hutool.core.io.FileUtil.getMimeType(java.lang.String)

Obtain MimeType based on file extension

cn.hutool.core.io.FileUtil.isSymlink(java.io.File)

Determine whether it is a symbolic link file

cn.hutool.core.io.FileUtil.isSub(java.io.File, java.io.File)

Judge whether a given directory is a subdirectory of a given file or folder

cn.hutool.core.io.FileUtil.createRandomAccessFile(java.nio.file.Path, cn.hutool.core.io.file.FileMode)

Create {@ link RandomAccessFile}

cn.hutool.core.io.FileUtil.createRandomAccessFile(java.io.File, cn.hutool.core.io.file.FileMode)

Create {@ link RandomAccessFile}

cn.hutool.core.io.FileUtil.tail(java.io.File, cn.hutool.core.io.LineHandler)

The file content follower realizes the function similar to the "tail -f" command under Linux
This method blocks the current thread

cn.hutool.core.io.FileUtil.tail(java.io.File, java.nio.charset.Charset, cn.hutool.core.io.LineHandler)

The file content follower realizes the function similar to the "tail -f" command under Linux
This method blocks the current thread

cn.hutool.core.io.FileUtil.tail(java.io.File, java.nio.charset.Charset)

The file content follower realizes the function similar to the "tail -f" command under Linux
This method blocks the current thread

cn.hutool.core.io.FileUtil.getName(java.io.File)

Return file name

cn.hutool.core.io.FileUtil.getName(java.lang.String)

Return file name

cn.hutool.core.io.FileUtil.getSuffix(java.io.File)

Get the file suffix without "."

cn.hutool.core.io.FileUtil.getSuffix(java.lang.String)

Get the file suffix without "."

cn.hutool.core.io.FileUtil.getPrefix(java.io.File)

Returns the main file name

cn.hutool.core.io.FileUtil.getPrefix(java.lang.String)

Returns the main file name

cn.hutool.core.io.FileUtil.mainName(java.io.File)

Returns the main file name

cn.hutool.core.io.FileUtil.mainName(java.lang.String)

Returns the main file name

cn.hutool.core.io.FileUtil.extName(java.io.File)

Gets the file extension (suffix) without "."

cn.hutool.core.io.FileUtil.extName(java.lang.String)

Get the extension (suffix) of the file without "."

cn.hutool.core.io.FileUtil.getLineSeparator()

Gets the newline separator of the current system

Windows:
Mac:
Linux:

Method details

Method name: CN hutool. core. io. FileUtil. isWindows()

Method description

Is it a Windows environment

Supported version and above

3.0.9

Parameter Description:

Parameter name

describe

Return value:

Is it a Windows environment

Reference case:

if( FileUtil.isWindows()){
			System.out.println("window environment");
		}else{
			System.out.println("Other environments");
		}

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. ls(java.lang.String)

Method description

List catalog files

The given absolute path cannot be a path in a compressed package

Supported version and above

Parameter Description:

Parameter name

describe

String path

Path directory absolute path or relative path

Return value:

File list (including directory)

Reference case:

		//List the files in the specified directory or the files in the subdirectory of the directory will not be listed
		File[] files = FileUtil.ls("D:\ruanjian");
		for(File file:files){
			System.out.println(file.getName());
		}

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. isEmpty(java.io.File)

Method description

Is the file empty

Directory: empty when there is no file in it. File: empty when the file size is 0

Supported version and above

Parameter Description:

Parameter name

describe

File file

File file

Return value:

Whether it is empty. It is true when the provided directory or file size is 0

Reference case:

		//Directory: empty when there are no files in it
		//File: empty when file size is 0
		Assert.assertEquals(Boolean.TRUE,FileUtil.isEmpty(new File("C:\Users\Administrator\Desktop\xuzhu\fileTest")));
		Assert.assertEquals(Boolean.FALSE,FileUtil.isEmpty(new File("C:\Users\Administrator\Desktop\xuzhu\copyTest1.txt")));
		Assert.assertEquals(Boolean.TRUE,FileUtil.isEmpty(new File("C:\Users\Administrator\Desktop\xuzhu\isEmptyTest.txt")));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. isNotEmpty(java.io.File)

Method description

Is the file not empty
Directory: empty when there is no file in it. File: empty when the file size is 0

Supported version and above

Parameter Description:

Parameter name

describe

File file

file directory

Return value:

Whether it is empty. It is false when the provided directory or file size is 0

Reference case:

		Assert.assertEquals(Boolean.FALSE,FileUtil.isNotEmpty(new File("C:\Users\Administrator\Desktop\xuzhu\fileTest")));
		Assert.assertEquals(Boolean.TRUE,FileUtil.isNotEmpty(new File("C:\Users\Administrator\Desktop\xuzhu\copyTest1.txt")));
		Assert.assertEquals(Boolean.FALSE,FileUtil.isNotEmpty(new File("C:\Users\Administrator\Desktop\xuzhu\isEmptyTest.txt")));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. isDirEmpty(java.io.File)

Method description

Is the directory empty

Supported version and above

Parameter Description:

Parameter name

describe

File dir

dir directory

Return value:

Is it empty

Reference case:

		//It must be the directory file, or an exception will be thrown
		Assert.assertEquals(Boolean.TRUE,FileUtil.isDirEmpty(new File("C:\Users\Administrator\Desktop\xuzhu\fileTest")));
		Assert.assertEquals(Boolean.FALSE,FileUtil.isDirEmpty(new File("C:\Users\Administrator\Desktop\xuzhu")));
		//Throw exception CN hutool. core. io. IORuntimeException: NotDirectoryException:
		Assert.assertEquals(Boolean.FALSE,FileUtil.isDirEmpty(new File("C:\Users\Administrator\Desktop\xuzhu\isEmptyTest.txt")));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. loopFiles(java.lang.String, java.io.FileFilter)

Method description

Recursively traverse all files in the directory and subdirectories

If the file provided is a file, the filtering result is returned directly

Supported version and above

3.2.0

Parameter Description:

Parameter name

describe

String path

Path the path to the current traversal file or directory

FileFilter fileFilter

fileFilter is a file filtering rule object. Select the file to keep. It is only valid for files and does not filter directories

Return value:

File list

Reference case:

		//Recursive traversal of directories and all files in subdirectories can be filtered
		List<File> files = FileUtil.loopFiles("C:\Users\Administrator\Desktop\xuzhu", new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				if(pathname.getName().indexOf("to")>-1){
					return true;
				}else{
					return false;
				}
			}
		});
		for(File file:files){
			System.out.println(file.getName());
		}

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. loopFiles(java.io.File, java.io.FileFilter)

Method description

Recursively traverse all files in the directory and subdirectories

If the file provided is a file, the filtering result is returned directly

Supported version and above

Parameter Description:

Parameter name

describe

File file

File currently traverses a file or directory

FileFilter fileFilter

fileFilter is a file filtering rule object. Select the file to keep. It is only valid for files and does not filter directories

Return value:

File list

Reference case:

		//Recursive traversal of directories and all files in subdirectories can be filtered
		List<File> files = FileUtil.loopFiles(new File("C:\Users\Administrator\Desktop\xuzhu"), new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				if(pathname.getName().indexOf("to")>-1){
					return true;
				}else{
					return false;
				}
			}
		});
		for(File file:files){
			System.out.println(file.getName());
		}

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. walkFiles(java.io.File, java.util.function.Consumer)

Method description

Recursively traverse the directory and process the files under the directory. You can process the directory or files:

  • If it is not a directory, it will directly call {@ link Consumer} for processing
  • This method is called recursively for directory processing

###Supported version and above 5.5.2 ### Parameter Description: parameter name | description - |--- file|

File file or directory, file processing directly

java.util.function.Consumer consumer |

consumer file processor, which can only process files

Return value:

Reference case:

		List<File> files = new ArrayList<>();
				//Recursively traverse the directory and process the files under the directory (subdirectories will also traverse), and you can process directories or files
		FileUtil.walkFiles(new File("C:\Users\Administrator\Desktop\xuzhu"), new Consumer<File>() {
			@Override
			public void accept(File file) {
				if(file.getName().indexOf("to")>-1){
					files.add(file);
				}
			}
		});
		for(File file:files){
			System.out.println(file.getName());
		}

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. loopFiles(java.io.File, int, java.io.FileFilter)

Method description

Recursively traverse all files in the directory and subdirectories

If the file provided is a file, the filtering result is returned directly

Supported version and above

4.6.3

Parameter Description:

Parameter name

describe

File file

File currently traverses a file or directory

int maxDepth

maxDepth traversal maximum depth, - 1 indicates traversal until there is no directory

FileFilter fileFilter

fileFilter is a file filtering rule object. Select the file to be retained. It is only valid for files and does not filter directories. null means to receive all files

Return value:

File list

Reference case:

		//Recursive traversal of directories and all files in subdirectories can be filtered
		List<File> files = FileUtil.loopFiles(new File("C:\Users\Administrator\Desktop\xuzhu"),3, new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				if(pathname.getName().indexOf("to")>-1){
					return true;
				}else{
					return false;
				}
			}
		});
		for(File file:files){
			System.out.println(file.getName());
		}

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. loopFiles(java.lang.String)

Method description

Recursively traverse all files in the directory and subdirectories

Supported version and above

3.2.0

Parameter Description:

Parameter name

describe

String path

Path the path to the current traversal file or directory

Return value:

File list

Reference case:

		//Recursively traverse all files in the directory and subdirectories
		List<File> files = FileUtil.loopFiles("C:\Users\Administrator\Desktop\xuzhu");
		for(File file:files){
			System.out.println(file.getName());
		}

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. loopFiles(java.io.File)

Method description

Recursively traverse all files in the directory and subdirectories

Supported version and above

Parameter Description:

Parameter name

describe

File file

File currently traverses the file

Return value:

File list

Reference case:

		//Recursively traverse all files in the directory and subdirectories
		List<File> files = FileUtil.loopFiles(new File("C:\Users\Administrator\Desktop\xuzhu"));
		for(File file:files){
			System.out.println(file.getName());
		}

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. listFileNames(java.lang.String)

Method description

Get all file names in the specified directory

Subdirectories will not be scanned

Supported version and above

Parameter Description:

Parameter name

describe

String path

Path is a directory relative to ClassPath or an absolute path directory

Return value:

List of all file names

Reference case:

		//Obtaining all file names in the specified directory will not scan subdirectories
		List<String> paths = FileUtil.listFileNames("C:\Users\Administrator\Desktop\xuzhu");
		for(String path:paths){
			System.out.println(path);
		}

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. newFile(java.lang.String)

Method description

Creating a File object is equivalent to calling new File() without any processing

Supported version and above

4.1.4

Parameter Description:

Parameter name

describe

String path

Path file path

Return value:

File

Reference case:

		//Creating a File object is equivalent to calling new File() without any processing
		File newfile = FileUtil.newFile("C:\Users\Administrator\Desktop\xuzhu

ewFile");
newfile.mkdirs();

Before directory call

After directory call

Source code analysis:

//I know everything
public static File newFile(String path) {
		return new File(path);
	}

Method details

Method name: CN hutool. core. io. FileUtil. file(java.lang.String)

Method description

Create a File object and automatically identify the relative or absolute path. The relative path will be automatically found under ClassPath

Supported version and above

Parameter Description:

Parameter name

describe

String path

Path file path

Return value:

File

Reference case:

		//Create a File object and automatically identify the relative or absolute path. The relative path will be automatically found under ClassPath
		File srcFile = FileUtil.file("hutool.jpg");
		Assert.assertEquals(Boolean.TRUE,srcFile.exists());
		srcFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\contentEqualsIgnoreEOLTest1.txt");
		Assert.assertEquals(Boolean.TRUE,srcFile.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. file(java.lang.String, java.lang.String)

Method description

Create File object

This method will check the slip vulnerability. See for the vulnerability description http://blog.nsfocus.net/zip-slip-2/

Supported version and above

Parameter Description:

Parameter name

describe

String parent

parent directory

String path

Path file path

Return value:

File

Reference case:

		//Create a File object. This method will check the slip vulnerability. See for the vulnerability description http://blog.nsfocus.net/zip-slip-2/
		File srcFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu","contentEqualsIgnoreEOLTest1.txt");
		Assert.assertEquals(Boolean.TRUE,srcFile.exists());
		//Unnecessary parent directory. This file should not be found
		srcFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\aaa","contentEqualsIgnoreEOLTest1.txt");
		Assert.assertEquals(Boolean.FALSE,srcFile.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. file(java.io.File, java.lang.String)

Method description

Create File object

According to the path construction file, it can be built directly under Win and separately under Linux
This method will check the slip vulnerability. See for the vulnerability description http://blog.nsfocus.net/zip-slip-2/

Supported version and above

Parameter Description:

Parameter name

describe

File parent

parent file object

String path

Path file path

Return value:

File

Reference case:

		//Create a File object. This method will check the slip vulnerability. See for the vulnerability description http://blog.nsfocus.net/zip-slip-2/
		File srcFile = FileUtil.file(new File("C:\Users\Administrator\Desktop\xuzhu"),"contentEqualsIgnoreEOLTest1.txt");
		Assert.assertEquals(Boolean.TRUE,srcFile.exists());
		//Unnecessary parent directory. This file should not be found
		srcFile = FileUtil.file(new File("C:\Users\Administrator\Desktop\xuzhu\aaa"),"contentEqualsIgnoreEOLTest1.txt");
		Assert.assertEquals(Boolean.FALSE,srcFile.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. file(java.io.File, java.lang.String[])

Method description

Create files with multi-level directory parameters

This method will check the slip vulnerability. See for the vulnerability description http://blog.nsfocus.net/zip-slip-2/

Supported version and above

4.0.6

Parameter Description:

Parameter name

describe

File directory

Directory parent directory

java.lang.String[] names

names element name (multi-layer directory name), which is passed in from outside to inside

Return value:

the file

Reference case:

		//Create a File object. This method will check the slip vulnerability. See for the vulnerability description http://blog.nsfocus.net/zip-slip-2/
		File srcFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu","loopFileTest","loopFileTest1","toLoopFlie1.txt");
		Assert.assertEquals(Boolean.TRUE,srcFile.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. file(java.lang.String[])

Method description

Create files from multiple directories

Element name (multi-level directory name) ### support version and above 4.0.6 ### Parameter Description: parameter name | description - | --- Java lang.String[] names |

names is the file name of multi-layer file, which is passed in from outside to inside

Return value:

the file

Reference case:

		//Create a File object, and the File name of multi-layer files is passed in from outside to inside
		File srcFile = FileUtil.file("C:","Users","Administrator","Desktop","xuzhu","loopFileTest","loopFileTest1","toLoopFlie1.txt");
		Assert.assertEquals(Boolean.TRUE,srcFile.exists());
		srcFile = FileUtil.file("C:","Users","Administrator","Desktop","xuzhu_nb","loopFileTest","loopFileTest1","toLoopFlie1.txt");
		Assert.assertEquals(Boolean.FALSE,srcFile.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. file(java.net.URI)

Method description

Create File object

Supported version and above

Parameter Description:

Parameter name

describe

URI uri

URI file URI

Return value:

File

Reference case:

		File srcFile = new File("C:\Users\Administrator\Desktop\xuzhu\contentEqualsIgnoreEOLTest1.txt");
		try {
			srcFile = FileUtil.file(srcFile.toURI());
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
		Assert.assertEquals(Boolean.TRUE,srcFile.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. file(java.net.URL)

Method description

Create File object

Supported version and above

Parameter Description:

Parameter name

describe

URL url

URL file URL

Return value:

File

Reference case:

		File srcFile = null;
		File file=new File("C:\Users\Administrator\Desktop\xuzhu\contentEqualsIgnoreEOLTest1.txt");
		try {
			URL url = file.toURI().toURL();
			System.out.println("url:"+url);
			srcFile = FileUtil.file(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Assert.assertEquals(Boolean.TRUE,srcFile.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getTmpDirPath()

Method description

Get temporary file path (absolute path)

Supported version and above

4.0.6

Parameter Description:

Parameter name

describe

Return value:

Temporary file path

Reference case:

		//Get temporary file path (absolute path) (temporary file path of current computer)
		System.out.println("Temporary file path:"+FileUtil.getTmpDirPath());

Source code analysis:

/**
	 * Get temporary file path (absolute path)
	 *
	 * @return Temporary file path
	 * @since 4.0.6
	 */
	public static String getTmpDirPath() {
		return System.getProperty("java.io.tmpdir");
	}

Method details

Method name: CN hutool. core. io. FileUtil. getTmpDir()

Method description

Get temporary file directory

Supported version and above

4.0.6

Parameter Description:

Parameter name

describe

Return value:

Temporary file directory

Reference case:

		//Get temporary file directory
		File temFile = FileUtil.getTmpDir();
		System.out.println("Temporary file directory:"+temFile.getPath());
		Assert.assertEquals(Boolean.TRUE,temFile.exists());

Source code analysis:

	/**
	 * Get temporary file directory
	 *
	 * @return Temporary file directory
	 * @since 4.0.6
	 */
	public static File getTmpDir() {
		return file(getTmpDirPath());
	}

Method details

Method name: CN hutool. core. io. FileUtil. getUserHomePath()

Method description

Get user path (absolute path)

Supported version and above

4.0.6

Parameter Description:

Parameter name

describe

Return value:

User path

Reference case:

		//Get user path (absolute path)
		System.out.println("Get user path (absolute path):"+FileUtil.getUserHomePath());

Source code analysis:

	/**
	 * Get user path (absolute path)
	 *
	 * @return User path
	 * @since 4.0.6
	 */
	public static String getUserHomePath() {
		return System.getProperty("user.home");
	}

Method details

Method name: CN hutool. core. io. FileUtil. getUserHomeDir()

Method description

Get user directory

Supported version and above

4.0.6

Parameter Description:

Parameter name

describe

Return value:

User directory

Reference case:

		//Get user directory
		File userHomeDir = FileUtil.getUserHomeDir();
		System.out.println("User directory:"+userHomeDir.getPath());
		Assert.assertEquals(Boolean.TRUE,userHomeDir.exists());

Source code analysis:

	/**
	 * Get user directory
	 *
	 * @return User directory
	 * @since 4.0.6
	 */
	public static File getUserHomeDir() {
		return file(getUserHomePath());
	}

Method details

Method name: CN hutool. core. io. FileUtil. exist(java.lang.String)

Method description

Judge whether the file exists. If the path is null, false will be returned

Supported version and above

Parameter Description:

Parameter name

describe

String path

Path file path

Return value:

Returns true if it exists

Reference case:

		String path ="C:\Users\Administrator\Desktop\xuzhu";
		Assert.assertEquals(Boolean.TRUE,FileUtil.exist(path));
		//Nonexistent path
		Assert.assertEquals(Boolean.FALSE,FileUtil.exist(path+"123"));
		path = null;
		Assert.assertEquals(Boolean.FALSE,FileUtil.exist(path));

		//Compared to file Exists() has the advantage of multi-path empty judgment processing
		//A null pointer NullPointerException will be thrown below
		File file = new File(path);
		Assert.assertEquals(Boolean.FALSE,file.exists());

Source code analysis:

	//The code is very clear, which is in the original file On the basis of exists(), the empty judgment processing of path is added
	/**
	 * Judge whether the file exists. If the path is null, false will be returned
	 *
	 * @param path File path
	 * @return Returns true if it exists
	 */
	public static boolean exist(String path) {
		return (null != path) && file(path).exists();
	}

Method details

Method name: CN hutool. core. io. FileUtil. exist(java.io.File)

Method description

Judge whether the file exists. If the file is null, false will be returned

Supported version and above

Parameter Description:

Parameter name

describe

File file

File file

Return value:

Returns true if it exists

Reference case:

		String path ="C:\Users\Administrator\Desktop\xuzhu";
		File file = new File(path);
		Assert.assertEquals(Boolean.TRUE,FileUtil.exist(file));
		//Nonexistent path
		file = new File(path+"123");
		Assert.assertEquals(Boolean.FALSE,FileUtil.exist(file));
		file = null;
		Assert.assertEquals(Boolean.FALSE,FileUtil.exist(file));

Source code analysis:

	/**
	 * Judge whether the file exists. If the file is null, false will be returned
	 *
	 * @param file file
	 * @return Returns true if it exists
	 */
	public static boolean exist(File file) {
		return (null != file) && file.exists();
	}

Method details

Method name: CN hutool. core. io. FileUtil. exist(java.lang.String, java.lang.String)

Method description

Is there a matching file

Supported version and above

Parameter Description:

Parameter name

describe

String directory

directory folder path

String regexp

Regular expressions for file names contained in the regexp folder

Return value:

Returns true if a matching file exists

Reference case:

		String path ="C:\Users\Administrator\Desktop\xuzhu";
		//Through the regular formula of matching file name, judge whether there is a matching file
		String regexp =  "contentEqualsIgnoreEOLTest(.*)";
		Assert.assertEquals(Boolean.TRUE,FileUtil.exist(path,regexp));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. lastModifiedTime(java.io.File)

Method description

Specifies when the file was last modified

Supported version and above

Parameter Description:

Parameter name

describe

File file

File file

Return value:

Last modification time

Reference case:

		File file=new File("C:\Users\Administrator\Desktop\xuzhu\contentEqualsIgnoreEOLTest1.txt");
		Date lastModifiedTime = FileUtil.lastModifiedTime(file);
		System.out.println(DateUtil.formatDateTime(lastModifiedTime));

Source code analysis:

stay file.lastModified()On the basis of file by null Judgment of
/**
	 * Specifies when the file was last modified
	 *
	 * @param file file
	 * @return Last modification time
	 */
	public static Date lastModifiedTime(File file) {
		if (false == exist(file)) {
			return null;
		}

		return new Date(file.lastModified());
	}

Method details

Method name: CN hutool. core. io. FileUtil. lastModifiedTime(java.lang.String)

Method description

Specifies when the path file was last modified

Supported version and above

Parameter Description:

Parameter name

describe

String path

Path absolute path

Return value:

Last modification time

Reference case:

		String path ="C:\Users\Administrator\Desktop\xuzhu\contentEqualsIgnoreEOLTest1.txt";
		Date lastModifiedTime = FileUtil.lastModifiedTime(path);
		System.out.println(DateUtil.formatDateTime(lastModifiedTime));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. size(java.io.File)

Method description

Calculate the total size of a directory or file

When the given object is a file, directly call {@ link File#length()}

When the given object is a directory, traverse all files and directories under the directory, recursively calculate its size, and return the sum

Supported version and above

Parameter Description:

Parameter name

describe

File file

File directory or file, null or file does not exist, return 0

Return value:

Total size, bytes, length

Reference case:

		//Calculate the total size of directories or files (subdirectories, subdirectories of subdirectories will also traverse) bytes
		String path ="C:\Users\Administrator\Desktop\xuzhu";
		//catalogue
		System.out.println(FileUtil.size(new File(path)));
		//file
		path ="C:\Users\Administrator\Desktop\xuzhu\contentEqualsIgnoreEOLTest1.txt";
		System.out.println(FileUtil.size(new File(path)));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. newerThan(java.io.File, java.io.File)

Method description

Is the last modification time of the given file or directory later than the given time

Supported version and above

Parameter Description:

Parameter name

describe

File file

file or directory

File reference

Reference reference file

Return value:

Is it later than the given time

Reference case:

		//Is the last modification time of the file or directory later than (greater than) the last modification time of the given file
		//When a given file does not exist, the file must be newer than a file that does not exist
		File file1=new File("C:\Users\Administrator\Desktop\xuzhu\contentEqualsIgnoreEOLTest1.txt");
		File file2=new File("C:\Users\Administrator\Desktop\xuzhu\contentEqualsIgnoreEOLTest2.txt");
		System.out.println("file1 Last modification time"+DateUtil.date(file1.lastModified()).toString());
		System.out.println("file2 Last modification time"+DateUtil.date(file2.lastModified()).toString());
		Assert.assertEquals(Boolean.FALSE,FileUtil.newerThan(file1,file2));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. newerThan(java.io.File, long)

Method description

Is the last modification time of the given file or directory later than the given time

Supported version and above

Parameter Description:

Parameter name

describe

File file

file or directory

long timeMillis

timeMillis as the time of comparison

Return value:

Is it later than the given time

Reference case:

		//Is the last modification time of the file or directory later than (greater than) the last modification time of the given file
		//When a given file does not exist, the file must be newer than a file that does not exist
		File file1=new File("C:\Users\Administrator\Desktop\xuzhu\contentEqualsIgnoreEOLTest1.txt");
		File file2=new File("C:\Users\Administrator\Desktop\xuzhu\contentEqualsIgnoreEOLTest2.txt");
		System.out.println("file1 Last modification time"+DateUtil.date(file1.lastModified()).toString());
		System.out.println("file2 Last modification time"+DateUtil.date(file2.lastModified()).toString());
		Assert.assertEquals(Boolean.FALSE,FileUtil.newerThan(file1,file2.lastModified()));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. touch(java.lang.String)

Method description

Create a file and its parent directory. If the file exists, return the file directly

The File type cannot be determined if the File method does not exist

Supported version and above

Parameter Description:

Parameter name

describe

String fullFilePath

The full path of fullFilePath file, using POSIX style

Return value:

File. If the path is null, null is returned

Reference case:

		// The full path of fullFilePath file, using POSIX style
		//Touch test Txt does not exist
		File file = FileUtil.touch("C:\Users\Administrator\Desktop\xuzhu\touchTest.txt");
		Assert.assertEquals(Boolean.TRUE,FileUtil.exist(file));
		//There are touchTest directory and touchTest Txt does not exist
		file = FileUtil.touch("C:\Users\Administrator\Desktop\xuzhu\touchTest\touchTest.txt");
		Assert.assertEquals(Boolean.TRUE,FileUtil.exist(file));

		String path = null;
		//If the path is null, null is returned
		file = FileUtil.touch(path);
		Assert.assertEquals(Boolean.FALSE,FileUtil.exist(file));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. touch(java.io.File)

Method description

Create a file and its parent directory. If the file exists, return the file directly

The File type cannot be determined if the File method does not exist

Supported version and above

Parameter Description:

Parameter name

describe

File file

file object

Return value:

File. If the path is null, null is returned

Reference case:

		// The full path of fullFilePath file, using POSIX style
		//Touch test Txt does not exist
		File file = FileUtil.touch(new File("C:\Users\Administrator\Desktop\xuzhu\touchTest.txt"));
		Assert.assertEquals(Boolean.TRUE,FileUtil.exist(file));
		//There are touchTest directory and touchTest Txt does not exist
		file = FileUtil.touch(new File("C:\Users\Administrator\Desktop\xuzhu\touchTest\touchTest.txt"));
		Assert.assertEquals(Boolean.TRUE,FileUtil.exist(file));

		file = null;
		//If file is null, null is returned
		file = FileUtil.touch(file);
		Assert.assertEquals(Boolean.FALSE,FileUtil.exist(file));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. touch(java.io.File, java.lang.String)

Method description

Create a file and its parent directory. If the file exists, return the file directly

The File type cannot be determined if the File method does not exist

Supported version and above

Parameter Description:

Parameter name

describe

File parent

parent file object

String path

Path file path

Return value:

File

Reference case:

		// The full path of fullFilePath file, using POSIX style
		//Touch test Txt does not exist
		File file = FileUtil.touch(new File("C:\Users\Administrator\Desktop\xuzhu"),"touchTest.txt");
		Assert.assertEquals(Boolean.TRUE,FileUtil.exist(file));
		//There are touchTest directory and touchTest Txt does not exist
		file = FileUtil.touch(new File("C:\Users\Administrator\Desktop\xuzhu\touchTest"),"touchTest.txt");
		Assert.assertEquals(Boolean.TRUE,FileUtil.exist(file));

		String path = null;
		//If the path is null, null is returned
		file = FileUtil.touch(path);
		Assert.assertEquals(Boolean.FALSE,FileUtil.exist(file));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. touch(java.lang.String, java.lang.String)

Method description

Create a file and its parent directory. If the file exists, return the file directly

The File type cannot be determined if the File method does not exist

Supported version and above

Parameter Description:

Parameter name

describe

String parent

parent file object

String path

Path file path

Return value:

File

Reference case:

		// The full path of fullFilePath file, using POSIX style
		//Touch test Txt does not exist
		File file = FileUtil.touch("C:\Users\Administrator\Desktop\xuzhu","touchTest.txt");
		Assert.assertEquals(Boolean.TRUE,FileUtil.exist(file));
		//There are touchTest directory and touchTest Txt does not exist
		file = FileUtil.touch("C:\Users\Administrator\Desktop\xuzhu\touchTest","touchTest.txt");
		Assert.assertEquals(Boolean.TRUE,FileUtil.exist(file));

		String path = null;
		//If the path is null, null is returned
		file = FileUtil.touch(path);
		Assert.assertEquals(Boolean.FALSE,FileUtil.exist(file));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. mkParentDirs(java.io.File)

Method description

Creates the parent directory of the given file or directory

Supported version and above

Parameter Description:

Parameter name

describe

File file

file or directory

Return value:

Parent directory

Reference case:

		//Create the parent directory of the given file or directory and return to the parent directory
		// Note: unlike touch, this will only create the parent directory, and the file will not be created
		File file = FileUtil.mkParentDirs(new File("C:\Users\Administrator\Desktop\xuzhu\mkParentDirs\mkParentDirsTest.txt"));
		System.out.println("File name:"+file.getName());
		Assert.assertEquals(Boolean.TRUE,FileUtil.exist(file));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. mkParentDirs(java.lang.String)

Method description

Create a parent folder and return to this folder directly if it exists

Supported version and above

Parameter Description:

Parameter name

describe

String path

Path folder path, using POSIX format, regardless of which platform

Return value:

Directory created

Reference case:

		//Create the parent directory of the given file or directory and return to the parent directory
		// Note: unlike touch, this will only create the parent directory, and the file will not be created
		File file = FileUtil.mkParentDirs("C:\Users\Administrator\Desktop\xuzhu\mkParentDirs\mkParentDirsTest.txt");
		System.out.println("File name:"+file.getName());
		Assert.assertEquals(Boolean.TRUE,FileUtil.exist(file));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. del(java.lang.String)

Method description

Delete files or folders

If the path is relative, it will be converted to ClassPath path path! Note: when deleting a folder, you will not judge whether the folder is empty. If it is not empty, you will recursively delete sub files or folders

A file deletion failure will terminate the deletion operation

Supported version and above

Parameter Description:

Parameter name

describe

String fullFileOrDirPath

fullFileOrDirPath the path to the file or directory

Return value:

Success or failure

Reference case:

		// To delete a file that does not exist, return true
		boolean result = FileUtil.del("e:/Hutool_test_3434543533409843.txt");
		Assert.assertTrue(result);

		//To delete an existing file, return true
		result = FileUtil.del("C:\Users\Administrator\Desktop\xuzhu\delTest\del1.txt");
		Assert.assertTrue(result);
		//To delete an existing folder, return true
		result = FileUtil.del("C:\Users\Administrator\Desktop\xuzhu\delTest\");
		Assert.assertTrue(result);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. del(java.io.File)

Method description

Delete files or folders

Note: when deleting a folder, you will not judge whether the folder is empty. If it is not empty, you will recursively delete sub files or folders

A file deletion failure will terminate the deletion operation

Supported version and above

Parameter Description:

Parameter name

describe

File file

file object

Return value:

Success or failure

Reference case:

		// To delete a file that does not exist, return true
		boolean result = FileUtil.del(new File("e:/Hutool_test_3434543533409843.txt"));
		Assert.assertTrue(result);

		//To delete an existing file, return true
		result = FileUtil.del(new File("C:\Users\Administrator\Desktop\xuzhu\delTest\del1.txt"));
		Assert.assertTrue(result);
		//To delete an existing folder, return true
		result = FileUtil.del(new File("C:\Users\Administrator\Desktop\xuzhu\delTest\"));
		Assert.assertTrue(result);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. clean(java.lang.String)

Method description

Empty Folder

Note: when emptying a folder, you will not judge whether the folder is empty. If it is not empty, you will recursively delete sub files or folders

A file deletion failure will terminate the deletion operation

Supported version and above

4.0.8

Parameter Description:

Parameter name

describe

String dirPath

dirPath folder path

Return value:

Success or failure

Reference case:

		//Empty an existing folder and return true
		boolean result = FileUtil.clean("C:\Users\Administrator\Desktop\xuzhu\cleanTest\");
		Assert.assertTrue(result);

Before emptying

After emptying

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. clean(java.io.File)

Method description

Empty Folder

Note: when emptying a folder, you will not judge whether the folder is empty. If it is not empty, you will recursively delete sub files or folders

A file deletion failure will terminate the deletion operation

Supported version and above

3.0.6

Parameter Description:

Parameter name

describe

File directory

directory folder

Return value:

Success or failure

Reference case:

		//Empty an existing folder and return true
		boolean result = FileUtil.clean(new File("C:\Users\Administrator\Desktop\xuzhu\cleanTest\"));
		Assert.assertTrue(result);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. cleanEmpty(java.io.File)

Method description

Clean up empty folders

This method is used to recursively delete empty folders without deleting files

If the incoming folder itself is empty, delete it

Supported version and above

4.5.5

Parameter Description:

Parameter name

describe

File directory

directory folder

Return value:

Success or failure

Reference case 1:

		//Clean up empty folders this folder contains an empty folder, a non empty folder, and a file
		boolean result = FileUtil.cleanEmpty(new File("C:\Users\Administrator\Desktop\xuzhu\cleanEmptyTest\"));
		Assert.assertTrue(result);

Reference case 2:

		//Clean up the empty folder. The incoming folder itself is empty. Delete this folder
		boolean result = FileUtil.cleanEmpty(new File("C:\Users\Administrator\Desktop\xuzhu\cleanEmptyTest1\"));
		Assert.assertTrue(result);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. mkdir(java.lang.String)

Method description

Create a folder and return to it directly if it exists

The File type cannot be determined if the File method does not exist

Supported version and above

Parameter Description:

Parameter name

describe

String dirPath

dirPath folder path, in POSIX format, regardless of platform

Return value:

Directory created

Reference case 1:

		String path = "C:\Users\Administrator\Desktop\xuzhu\mkdirTest\mkdirTest1";
		//When you create a folder, you will recursively and automatically create its nonexistent parent folder. If it does exist, you will directly return to this folder
		File dirFir = FileUtil.mkdir(path);
		Assert.assertEquals(Boolean.TRUE,dirFir.exists());

Reference case 2:

		String path = "C:\Users\Administrator\Desktop\xuzhu\mkdirTest\mkdirTest1\mkdirTest1.txt";
		//The file name at the end of the file path will also become the name of the folder
		File dirFir = FileUtil.mkdir(path);
		Assert.assertEquals(Boolean.TRUE,dirFir.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. mkdir(java.io.File)

Method description

When you create a folder, you will recursively and automatically create its nonexistent parent folder. If it does exist, you will directly return to this folder

The File type cannot be determined if the File method does not exist

Supported version and above

Parameter Description:

Parameter name

describe

File dir

dir directory

Return value:

Directory created

Reference case:

		String path = "C:\Users\Administrator\Desktop\xuzhu\mkdirTest\mkdirTest1";
		//When you create a folder, you will recursively and automatically create its nonexistent parent folder. If it does exist, you will directly return to this folder
		File dirFir = FileUtil.mkdir(new File(path));
		Assert.assertEquals(Boolean.TRUE,dirFir.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. createTempFile(java.io.File)

Method description

Create temporary file

The created file name is prefix [random] tmp

Supported version and above

Parameter Description:

Parameter name

describe

File dir

dir directory where temporary files are created

Return value:

Temporary documents

Reference case:

		String path = "C:\Users\Administrator\Desktop\xuzhu\createTempFileTest\";
		//Create a temporary file. The file name after creation is hutool [random] tmp
		File tempFile = FileUtil.createTempFile(new File(path));
		System.out.println("Path:"+tempFile.getPath());
		System.out.println("file name:"+tempFile.getName());
		Assert.assertEquals(Boolean.TRUE,tempFile.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. createTempFile(java.io.File, boolean)

Method description

Create temporary file

The created file name is prefix [random] tmp

Supported version and above

Parameter Description:

Parameter name

describe

File dir

dir directory where temporary files are created

boolean isReCreat

isReCreat whether to recreate the file (delete the original and create a new one)

Return value:

Temporary documents

Reference case:

		String path = "C:\Users\Administrator\Desktop\xuzhu\createTempFileTest\";
		//Create a temporary file. The file name after creation is hutool [random] TMP isrecreat whether to recreate the file (delete the original and create a new one)
		File tempFile = FileUtil.createTempFile(new File(path),Boolean.TRUE);
		System.out.println("Path:"+tempFile.getPath());
		System.out.println("file name:"+tempFile.getName());
		Assert.assertEquals(Boolean.TRUE,tempFile.exists());
		tempFile = FileUtil.createTempFile(new File(path),Boolean.TRUE);
		System.out.println("Path:"+tempFile.getPath());
		System.out.println("file name:"+tempFile.getName());
		Assert.assertEquals(Boolean.TRUE,tempFile.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. createTempFile(java.lang.String, java.lang.String, java.io.File, boolean)

Method description

Create temporary file

The created file name is prefix [random] suffix From com. jodd. io. FileUtil

Supported version and above

Parameter Description:

Parameter name

describe

String prefix

Prefix prefix, at least 3 characters

String suffix

Suffix. If null, the default suffix is used tmp

File dir

dir directory where temporary files are created

boolean isReCreat

isReCreat whether to recreate the file (delete the original and create a new one)

Return value:

Temporary documents

Reference case:

		String path = "C:\Users\Administrator\Desktop\xuzhu\createTempFileTest\";
		String prefix="xuzhu";
		String suffix=".nb";
		//Create a temporary file. The file name after creation is hutool [random] TMP isrecreat whether to recreate the file (delete the original and create a new one)
		File tempFile = FileUtil.createTempFile(prefix,suffix,new File(path),Boolean.TRUE);
		System.out.println("Path:"+tempFile.getPath());
		System.out.println("file name:"+tempFile.getName());
		Assert.assertEquals(Boolean.TRUE,tempFile.exists());
		tempFile = FileUtil.createTempFile(prefix,suffix,new File(path),Boolean.TRUE);
		System.out.println("Path:"+tempFile.getPath());
		System.out.println("file name:"+tempFile.getName());
		Assert.assertEquals(Boolean.TRUE,tempFile.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. copyFile(java.lang.String, java.lang.String, java.nio.file.StandardCopyOption[])

Method description

Copy files through the Files#copy(Path, Path, CopyOption...) method of JDK7 +

Supported version and above

Parameter Description:

Parameter name

describe

String src

src source file path

String dest

dest destination file or directory path. If it is a directory, use the same file name as the source file

java.nio.file.StandardCopyOption[] options

options {@link StandardCopyOption}

Return value:

File

Reference case 1:

		//copyTest1.txt exists, copytest2 Txt does not exist
		String srcPath = "C:\Users\Administrator\Desktop\xuzhu\copyFileTest\copyTest1.txt";
		String destPath = "C:\Users\Administrator\Desktop\xuzhu\copyFileTest\copyTest2.txt";
		//Returns the file copy operation of the destination dest
		//StandardCopyOption.COPY_ATTRIBUTES: completely copy the attributes of the source file to the new file. Note: the target file must not exist, or an error will be reported (FileAlreadyExistsException: * * *)
		File copyFile = FileUtil.copyFile(srcPath,destPath, StandardCopyOption.COPY_ATTRIBUTES);
		Assert.assertEquals(Boolean.TRUE,copyFile.exists());

Before copying:

After copying:

After copying, execute the code

Reference case 2:

		//copyTest1.txt exists, copytest2 txt,copyTest3.txt does not exist
		String srcPath = "C:\Users\Administrator\Desktop\xuzhu\copyFileTest1\copyTest1.txt";
		String destPath = "C:\Users\Administrator\Desktop\xuzhu\copyFileTest1\copyTest2.txt";
		String destPath3 = "C:\Users\Administrator\Desktop\xuzhu\copyFileTest1\copyTest3.txt";
		//Returns the file copy operation of the destination dest
		File copyFile = FileUtil.copyFile(srcPath,destPath, StandardCopyOption.COPY_ATTRIBUTES);
		FileUtil.copyFile(srcPath,destPath3, StandardCopyOption.COPY_ATTRIBUTES);
		Assert.assertEquals(Boolean.TRUE,copyFile.exists());

		//If the target path already exists (that is, the copyTest2.txt file), the copy or move will fail.
		// If you want to overwrite the existing target path, you can use replace_ The existing option. If you want to copy the attributes of all files, you can use COPY_ATTRIBUTES option. You can also use both options
		srcPath = "C:\Users\Administrator\Desktop\xuzhu\copyFileTest1\copyTest1.txt";
		destPath = "C:\Users\Administrator\Desktop\xuzhu\copyFileTest1\copyTest2.txt";
		copyFile = FileUtil.copyFile(srcPath,destPath, StandardCopyOption.REPLACE_EXISTING);
		Assert.assertEquals(Boolean.TRUE,copyFile.exists());
		srcPath = "C:\Users\Administrator\Desktop\xuzhu\copyFileTest1\copyTest1.txt";
		destPath = "C:\Users\Administrator\Desktop\xuzhu\copyFileTest1\copyTest3.txt";
		copyFile = FileUtil.copyFile(srcPath,destPath, StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.COPY_ATTRIBUTES);
		Assert.assertEquals(Boolean.TRUE,copyFile.exists());

Before copying:

After copying:

Reference case 3:

		//copyTest1.txt exists, copytest2 Txt does not exist
		String srcPath = "C:\Users\Administrator\Desktop\xuzhu\copyFileTest2\copyTest1.txt";
		String destPath = "C:\Users\Administrator\Desktop\xuzhu\copyFileTest2\copyTest2.txt";
		//Returns the file copy operation of the destination dest
		//StandardCopyOption.ATOMIC_MOVE: move the file as an atomic file system operation. An error will be reported: (unsupported operationexception: Unsupported copy option) because the copy method cannot use this parameter
		//By the way, the attributes supported by copy are: (see windowsfilecopy. Java for details)
		// StandardCopyOption.REPLACE_EXISTING  
		// LinkOption.NOFOLLOW_LINKS 
		// StandardCopyOption.COPY_ATTRIBUTES 
		// ExtendedCopyOption.INTERRUPTIBLE
		File copyFile = FileUtil.copyFile(srcPath,destPath, StandardCopyOption.ATOMIC_MOVE);
		Assert.assertEquals(Boolean.TRUE,copyFile.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. copyFile(java.io.File, java.io.File, java.nio.file.StandardCopyOption[])

Method description

Copy files through the Files#copy(Path, Path, CopyOption...) method of JDK7 +

Supported version and above

Parameter Description:

Parameter name

describe

File src

src source file

File dest

dest target file or directory. If it is a directory, use the same file name as the source file

java.nio.file.StandardCopyOption[] options

options {@link StandardCopyOption}

Return value:

Target file

Reference case:

		//copyTest1.txt exists, copytest2 Txt does not exist
		String srcPath = "C:\Users\Administrator\Desktop\xuzhu\copyFileTest3\copyTest1.txt";
		String destPath = "C:\Users\Administrator\Desktop\xuzhu\copyFileTest3\copyTest2.txt";
		//Returns the file copy operation of the destination dest
		//StandardCopyOption. COPY_ If the target file exists, it will be reported that the file exists completely (otherwise, it will be reported that the file cannot be copied to the target file with the error of "attriexception": * * *)
		File copyFile = FileUtil.copyFile(new File(srcPath),new File(destPath), StandardCopyOption.COPY_ATTRIBUTES);
		Assert.assertEquals(Boolean.TRUE,copyFile.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. copy(java.lang.String, java.lang.String, boolean)

Method description

Copy files or directories

If the destination file is a directory, copy the source file to the destination directory with the same file name

Supported version and above

Parameter Description:

Parameter name

describe

String srcPath

srcPath source file or directory

String destPath

destPath target file or directory. If the target does not exist, it will be created automatically (both directory and file will be created)

boolean isOverride

Does isOverride overwrite the target file

Return value:

Destination directory or file

Reference case:

		String srcPath = "hutool.jpg";
		String destPath = "hutool.copy.jpg";
		File destFile = FileUtil.copy(srcPath, destPath, true);
		Assert.assertTrue(destFile.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. copy(java.io.File, java.io.File, boolean)

Method description

Copy files or directories

The situation is as follows:

1. If both src and dest are directories, copy the src directory and all file directories under it to dest
2. src and dest are files, which are copied directly and named dest
3. src is a file and dest is a directory. Copy src to dest directory

Supported version and above

Parameter Description:

Parameter name

describe

File src

src source file

File dest

dest target file or directory. If the target does not exist, it will be created automatically (both directory and file will be created)

boolean isOverride

Does isOverride overwrite the target file

Return value:

Destination directory or file

Reference case:

		File srcFile = FileUtil.file("hutool.jpg");
		File destFile = FileUtil.file("hutool.copy.jpg");

		FileUtil.copy(srcFile, destFile, true);

		Assert.assertTrue(destFile.exists());
		Assert.assertEquals(srcFile.length(), destFile.length());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. copyContent(java.io.File, java.io.File, boolean)

Method description

Copy files or directories

The situation is as follows:

1. If both src and dest are directories, all files and directories under src are copied to dest
2. src and dest are files, which are copied directly and named dest
3. src is a file and dest is a directory. Copy src to dest directory

Supported version and above

Parameter Description:

Parameter name

describe

File src

src source file

File dest

dest target file or directory. If the target does not exist, it will be created automatically (both directory and file will be created)

boolean isOverride

Does isOverride overwrite the target file

Return value:

Destination directory or file

Reference case 1:

		//1. If both src and dest are directories, all files and directories under src are copied to dest
		String srcPath = "C:\Users\Administrator\Desktop\xuzhu\copyContentTest1";
		String destPath = "C:\Users\Administrator\Desktop\xuzhu\copyContentTest1_dest";
		//The returned object file is the target directory or file
		FileUtil.copyContent(new File(srcPath),new File(destPath),true);

Before copying

After copying: if the target directory does not exist, the program will help create the directory

Reference case 2:

		//2. src and dest are files, which are copied directly and named dest
		String srcPath = "C:\Users\Administrator\Desktop\xuzhu\copyContentTest1\copyTest1.txt";
		String destPath = "C:\Users\Administrator\Desktop\xuzhu\copyContentTest1\copyTest2.txt";
		//The returned object file is the target directory or file
		FileUtil.copyContent(new File(srcPath),new File(destPath),true);

Reference case 3:

		//3. src is a file and dest is a directory. Copy src to dest directory
		String srcPath = "C:\Users\Administrator\Desktop\xuzhu\copyContentTest1\copyTest1.txt";
		//dest is a directory and must exist, otherwise the replication will not succeed
		String destPath = "C:\Users\Administrator\Desktop\xuzhu\copyContentTest3\";
		//The returned object file is the target directory or file
		FileUtil.copyContent(new File(srcPath),new File(destPath),true);

Reference case 4:

		//1. If both src and dest are directories, all file directories under src will be copied to DeST (including subdirectories, subdirectories will be copied, and files contained in subdirectories will also be copied)
		String srcPath = "C:\Users\Administrator\Desktop\xuzhu\copyContentTest4";
		String destPath = "C:\Users\Administrator\Desktop\xuzhu\copyContentTest4_dest";
		//The returned object file is the target directory or file
		FileUtil.copyContent(new File(srcPath),new File(destPath),true);

Before copying:

After copying:

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. copyFilesFromDir(java.io.File, java.io.File, boolean)

Method description

Copy files or directories

The situation is as follows:

1. If both src and dest are directories, all files (including subdirectories) under src are copied to dest
2. src and dest are files, which are copied directly and named dest
3. src is a file and dest is a directory. Copy src to dest directory

Supported version and above

4.1.5

Parameter Description:

Parameter name

describe

File src

src source file

File dest

dest target file or directory. If the target does not exist, it will be created automatically (both directory and file will be created)

boolean isOverride

Does isOverride overwrite the target file

Return value:

Destination directory or file

Reference case:

//1. If both src and dest are directories, all files (including subdirectories) under src are copied to dest
		String srcPath = "C:\Users\Administrator\Desktop\xuzhu\copyFilesFromDirTest1";
		String destPath = "C:\Users\Administrator\Desktop\xuzhu\copyFilesFromDirTest1_dest";
		//The returned object file is the target directory or file
		FileUtil.copyContent(new File(srcPath),new File(destPath),true);

Reference case 2:

		//1. If both src and dest are directories, all files (including subdirectories) under src are copied to dest
		String srcPath = "C:\Users\Administrator\Desktop\xuzhu\copyFilesFromDirTest2";
		String destPath = "C:\Users\Administrator\Desktop\xuzhu\copyFilesFromDirTest2_dest";
		//The returned object file is the target directory or file
		FileUtil.copyContent(new File(srcPath),new File(destPath),true);

Before copying:

After copying:

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. move(java.io.File, java.io.File, boolean)

Method description

Move files or directories

Supported version and above

Parameter Description:

Parameter name

describe

File src

src source file or directory

File target

Target target file or directory

boolean isOverride

Whether isOverride overwrites the target. Only files with the target can be overwritten

Return value:

Reference case:

		//1. Move directory to directory
		File srcFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\moveTest");
		//The target directory does not exist, and the program will help create it
		File destFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\targetMoveTest");

		FileUtil.move(srcFile, destFile, true);

Before moving:

After moving:

Reference case 2:

		//2. Move the source file of directory A to directory B
		File srcFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\moveTest2\moveTest2.txt");
		//The target directory / dest is a directory and must exist. Otherwise, the move will not succeed and will become a file
		File destFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\targetMoveTest2\");

		FileUtil.move(srcFile, destFile, true);

Before moving:

After moving:

Reference case 3:

		//3. Move the source file of directory A to the target file of directory B
		File srcFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\moveTest3\moveTest3.txt");
		//The target directory does not exist, and the program will help create it
		File destFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\targetMoveTest3\moveTest3.txt");

		FileUtil.move(srcFile, destFile, true);

Before moving:

After moving:

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. rename(java.io.File, java.lang.String, boolean)

Method description

Modify the file name of a file or directory without changing the path, but simply modify the file name without retaining the extension.

FileUtil.rename(file, "aaa.png", true) xx/xx.png =>xx/aaa.png

Supported version and above

5.3.6

Parameter Description:

Parameter name

describe

File file

File modified file

String newName

newName is a new file name. If you need an extension, you need to add it to this parameter by yourself. The extension of the original file name will not be retained

boolean isOverride

Does isOverride overwrite the target file

Return value:

Target file

Reference case:

		FileUtil.rename(FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\renameTest\hutool.jpg"), "hutool2.jpg", false);

Before modification:

After modification:

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. rename(java.io.File, java.lang.String, boolean, boolean)

Method description

Modify the file name of a file or directory without changing the path, but simply modify the file name

There are two modes of renaming:

1. When isRetainExt is true, keep the original extension:

FileUtil.rename(file, "aaa", true) xx/xx.png =>xx/aaa.png

2. When isRetainExt is false, the original extension is not retained and needs to be in newName

FileUtil.rename(file, "aaa.jpg", false) xx/xx.png =>xx/aaa.jpg

Supported version and above

3.0.9

Parameter Description:

Parameter name

describe

File file

File modified file

String newName

newName new file name, including extension

boolean isRetainExt

isRetainExt whether to keep the extension of the original file. If so, newName does not need to add an extension

boolean isOverride

Does isOverride overwrite the target file

Return value:

Target file

Reference case:

		//isRetainExt whether to keep the extension of the original file. If so, newName does not need to add an extension
		FileUtil.rename(FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\renameTest3\hutool.jpg"), "hutool2",Boolean.TRUE, false);
		FileUtil.rename(FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\renameTest3\hutool1.jpg"), "hutool3.jpg",Boolean.FALSE, false);

Before modification:

After modification:

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getCanonicalPath(java.io.File)

Method description

Gets the absolute path of the specification

Supported version and above

4.1.4

Parameter Description:

Parameter name

describe

File file

File file

Return value:

Specifies the absolute path. If the incoming file is null, null is returned

Reference case:

		//Gets the absolute path of the specification
		System.out.println(FileUtil.getCanonicalPath(new File("C:\Users\Administrator\Desktop\xuzhu\copyTest1.txt")));
		//If the incoming file is null, null is returned
		File file = null;
		System.out.println(FileUtil.getCanonicalPath(file));
		//If the incoming path does not exist, it can also be obtained
		System.out.println(FileUtil.getCanonicalPath(new File("C:\Users\Administrator\Desktop\getCanonicalPathTest\copyTest1.txt")));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getAbsolutePath(java.lang.String, java.lang.Class)

Method description

Get absolute path

This method does not determine whether the given path is valid (file or directory exists)

Supported version and above

Parameter Description:

Parameter name

describe

String path

Path relative path

java.lang.Class baseClass

baseClass the class to which the relative path is relative

Return value:

Absolute path

Reference case:

			//Get the absolute path, and the files in the jar package can also be searched relative to the directory of ClassPath
		String absolutePath = FileUtil.getAbsolutePath("FileUtil.class",FileUtil.class);
		Assert.assertNotNull(absolutePath);
		System.out.println("absolutePath:"+absolutePath);	

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getAbsolutePath(java.lang.String)

Method description

Gets the absolute path, relative to the directory of ClassPath

If the given is an absolute path, the original path is returned, and the original path replaces all with/

Compatible with Spring style path representation, for example: classpath: config / example Setting will also be converted after being recognized

Supported version and above

Parameter Description:

Parameter name

describe

String path

Path relative path

Return value:

Absolute path

Reference case:

		//Get the absolute path. Relative to the directory of ClassPath, the files in the jar package can also be searched
		String absolutePath = FileUtil.getAbsolutePath("LICENSE-junit.txt");
		Assert.assertNotNull(absolutePath);
		System.out.println("absolutePath:"+absolutePath);
		String absolutePath2 = FileUtil.getAbsolutePath(absolutePath);
		Assert.assertNotNull(absolutePath2);
		System.out.println("absolutePath2:"+absolutePath2);
		Assert.assertEquals(absolutePath, absolutePath2);

		String path = FileUtil.getAbsolutePath("chinese.xml");
		Assert.assertTrue(path.contains("chinese.xml"));
		System.out.println("path:"+path);

		path = FileUtil.getAbsolutePath("d:");
		Assert.assertEquals("d:", path);
		System.out.println("path:"+path);

"Chinese. xml" does not exist, but the path can still get "relative to ClassPath"

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getAbsolutePath(java.io.File)

Method description

Get standard absolute path

Supported version and above

Parameter Description:

Parameter name

describe

File file

File file

Return value:

Absolute path

Reference case:

		//Getting the standard absolute path is different from getAbsolutePath (String)
		String absolutePath = FileUtil.getAbsolutePath(new File("LICENSE-junit.txt"));
		Assert.assertNotNull(absolutePath);
		System.out.println("absolutePath:"+absolutePath);
		String absolutePath2 = FileUtil.getAbsolutePath(new File(absolutePath));
		Assert.assertNotNull(absolutePath2);
		System.out.println("absolutePath2:"+absolutePath2);
		Assert.assertEquals(absolutePath, absolutePath2);

		String path = FileUtil.getAbsolutePath(new File("chinese.xml"));
		Assert.assertTrue(path.contains("chinese.xml"));
		System.out.println("path:"+path);

		path = FileUtil.getAbsolutePath(new File("d:"));
		System.out.println("path:"+path);

Source code analysis:

if (file == null) {
			return null;
		}

		try {
			return file.getCanonicalPath();
		} catch (IOException e) {
			return file.getAbsolutePath();
		}
		The source code is very simple, which is a blank judgment and direct return file.getCanonicalPath()
It will be analyzed in source code analysis: getCanonicalPath and getAbsolutePath Differences between
 Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. isAbsolutePath(java.lang.String)

Method description

The given path is already an absolute path

This method does not standardize the path. It is recommended to execute the {@ link #normalize(String)} method to standardize the path before judgment

Supported version and above

Parameter Description:

Parameter name

describe

String path

Path path to check

Return value:

Is it already an absolute path

Reference case:

		//Repaired path
		String path = FileUtil.normalize("C:\Users\Administrator\Desktop\xuzhu\isAbsolutePathTest\isAbsolutePathTest.txt");
		//Is it already an absolute path
		Assert.assertEquals(Boolean.TRUE,FileUtil.isAbsolutePath(path));
		path = FileUtil.normalize("FileUtil.class");
		//Is it already an absolute path
		Assert.assertEquals(Boolean.FALSE,FileUtil.isAbsolutePath(path));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. isDirectory(java.lang.String)

Method description

Judge whether it is a directory. If the path is null, false will be returned

Supported version and above

Parameter Description:

Parameter name

describe

String path

Path file path

Return value:

If directory is true

Reference case:

		//Determine whether it is a directory
		String path = "C:\Users\Administrator\Desktop\xuzhu\";
		Assert.assertEquals(Boolean.TRUE,FileUtil.isDirectory(path));
		path = null;
		Assert.assertEquals(Boolean.FALSE,FileUtil.isDirectory(path));
		path = "C:\Users\Administrator\Desktop\xuzhu\copyTest1.txt";
		Assert.assertEquals(Boolean.FALSE,FileUtil.isDirectory(path));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. isDirectory(java.io.File)

Method description

Judge whether it is a directory. If file is null, false will be returned

Supported version and above

Parameter Description:

Parameter name

describe

File file

File file

Return value:

If directory is true

Reference case:

		//Determine whether it is a directory
		String path = "C:\Users\Administrator\Desktop\xuzhu\";
		Assert.assertEquals(Boolean.TRUE,FileUtil.isDirectory(new File(path)));
		File file = null;
		Assert.assertEquals(Boolean.FALSE,FileUtil.isDirectory(file));
		path = "C:\Users\Administrator\Desktop\xuzhu\copyTest1.txt";
		Assert.assertEquals(Boolean.FALSE,FileUtil.isDirectory(new File(path)));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. isFile(java.lang.String)

Method description

Judge whether it is a file. If the path is null, false will be returned

Supported version and above

Parameter Description:

Parameter name

describe

String path

Path file path

Return value:

If file is true

Reference case:

		//Determine whether it is a file
		String path = "C:\Users\Administrator\Desktop\xuzhu\";
		Assert.assertEquals(Boolean.FALSE,FileUtil.isFile(path));
		path = null;
		Assert.assertEquals(Boolean.FALSE,FileUtil.isFile(path));
		path = "C:\Users\Administrator\Desktop\xuzhu\copyTest1.txt";
		Assert.assertEquals(Boolean.TRUE,FileUtil.isFile(path));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. isFile(java.io.File)

Method description

Judge whether it is a file. If the file is null, false will be returned

Supported version and above

Parameter Description:

Parameter name

describe

File file

File file

Return value:

If file is true

Reference case:

		//Determine whether it is a file
		String path = "C:\Users\Administrator\Desktop\xuzhu\";
		Assert.assertEquals(Boolean.FALSE,FileUtil.isFile(new File(path)));
		File file = null;
		Assert.assertEquals(Boolean.FALSE,FileUtil.isFile(file));
		path = "C:\Users\Administrator\Desktop\xuzhu\copyTest1.txt";
		Assert.assertEquals(Boolean.TRUE,FileUtil.isFile(new File(path)));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. equals(java.io.File, java.io.File)

Method description

Check whether the two files are the same file

The same File refers to whether the File object points to the same File or folder

Supported version and above

Parameter Description:

Parameter name

describe

File file1

file1 file 1

File file2

file2 file 2

Return value:

Are they the same

Reference case:

		// Neither the source file nor the target file exists
		File srcFile = FileUtil.file("d:/hutool.jpg");
		File destFile = FileUtil.file("d:/hutool.jpg");

		boolean equals = FileUtil.equals(srcFile, destFile);
		Assert.assertTrue(equals);

		// Source file exists, target file does not exist
		File srcFile1 = FileUtil.file("hutool.jpg");
		File destFile1 = FileUtil.file("d:/hutool.jpg");

		boolean notEquals = FileUtil.equals(srcFile1, destFile1);
		Assert.assertFalse(notEquals);

		//The source folder and destination folder do not exist
		File srcFile2 = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu1\");
		File destFile2 = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu1\");
		Assert.assertEquals(Boolean.TRUE,FileUtil.equals(srcFile2, destFile2));
		//The source folder and destination folder are the same and exist
		File srcFile3 = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\");
		File destFile3 = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\");
		Assert.assertEquals(Boolean.TRUE,FileUtil.equals(srcFile3, destFile3));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. contentEquals(java.io.File, java.io.File)

Method description

Compare whether the contents of the two files are the same

First compare the length, and then compare the content if the length is consistent

This method is from Apache Commons io

Supported version and above

4.0.6

Parameter Description:

Parameter name

describe

File file1

file1 file 1

File file2

file2 file 2

Return value:

If the contents of the two files are consistent, return true, otherwise false

Reference case:

		// Compare whether the contents of two files are the same. You can't compare two folders. In the method, you can judge whether they are folders. If yes, you will be prompted with an error
		// Source file exists, target file does not exist
		File srcFile1 = FileUtil.file("hutool.jpg");
		File destFile1 = FileUtil.file("d:/hutool.jpg");
		Assert.assertEquals(Boolean.FALSE,FileUtil.contentEquals(srcFile1, destFile1));

		// Source file exists, target file exists
		File srcFile2 = FileUtil.file("hutool.jpg");
		File destFile2 = FileUtil.file("hutool.jpg");
		Assert.assertEquals(Boolean.TRUE,FileUtil.contentEquals(srcFile2, destFile2));

		// Source file exists, target file exists
		File srcFile3 = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\copyTest1.txt");
		File destFile3 = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\toCopyTest1.txt");
		Assert.assertEquals(Boolean.TRUE,FileUtil.contentEquals(srcFile3, destFile3));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. contentEqualsIgnoreEOL(java.io.File, java.io.File, java.nio.charset.Charset)

Method description

Compare whether the contents of the two files are the same

First, compare the length, and then compare the content. The comparison content is read by line, and each line is compared

This method is from Apache Commons io

Supported version and above

4.0.6

Parameter Description:

Parameter name

describe

File file1

file1 file 1

File file2

file2 file 2

Charset charset

charset encoding, null indicates that the platform default encoding is used, and the contents of the two files are consistent. Return true, otherwise false

Return value:

Are they the same

Reference case:

		// Compare whether the contents of two files are the same. You can't compare two folders. In the method, you can judge whether they are folders. If yes, you will be prompted with an error
		// Source file exists, target file does not exist
		File srcFile1 = FileUtil.file("hutool.jpg");
		File destFile1 = FileUtil.file("d:/hutool.jpg");
		Assert.assertEquals(Boolean.FALSE,FileUtil.contentEqualsIgnoreEOL(srcFile1, destFile1, CharsetUtil.CHARSET_UTF_8));

		// Source file exists, target file exists
		File srcFile2 = FileUtil.file("hutool.jpg");
		File destFile2 = FileUtil.file("hutool.jpg");
		Assert.assertEquals(Boolean.TRUE,FileUtil.contentEqualsIgnoreEOL(srcFile2, destFile2,CharsetUtil.CHARSET_UTF_8));

		// Source file exists, target file exists
		File srcFile3 = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\copyTest1.txt");
		File destFile3 = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\toCopyTest1.txt");
		Assert.assertEquals(Boolean.TRUE,FileUtil.contentEqualsIgnoreEOL(srcFile3, destFile3,CharsetUtil.CHARSET_UTF_8));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. pathEquals(java.io.File, java.io.File)

Method description

Are the file paths the same

Compare the absolute paths of the two files, ignoring case in Windows and not in Linux.

Supported version and above

3.0.9

Parameter Description:

Parameter name

describe

File file1

file1 file 1

File file2

file2 file 2

Return value:

Are the file paths the same

Reference case:

//Whether the file paths are the same takes the absolute path comparison of the two files rather than the parent directory comparison of the files
		File srcFile3 = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\copyTest1.txt");
		File destFile3 = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\toCopyTest1.txt");
		Assert.assertEquals(Boolean.FALSE,FileUtil.pathEquals(srcFile3, destFile3));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. lastIndexOfSeparator(java.lang.String)

Method description

Gets the location of the last file path separator

Supported version and above

Parameter Description:

Parameter name

describe

String filePath

filePath file path

Return value:

Location of the last file path separator

Reference case:

		String dir = "d:\aaa\bbb\cc\ddd";
		int index = FileUtil.lastIndexOfSeparator(dir);
		Assert.assertEquals(13, index);

		String file = "ddd.jpg";
		int index2 = FileUtil.lastIndexOfSeparator(file);
		Assert.assertEquals(-1, index2);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. isModifed(java.io.File, long)

Method description

Determine whether the file has been changed

If the file object is null or the file does not exist, it is regarded as a change

Supported version and above

Parameter Description:

Parameter name

describe

File file

file object

long lastModifyTime

lastModifyTime last change time

Return value:

Is it changed

Reference case:

		File srcFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\copyTest1.txt");
		//Determine whether the file has been changed
		Assert.assertEquals(Boolean.FALSE,FileUtil.isModifed(srcFile,srcFile.lastModified()));
		Assert.assertEquals(Boolean.TRUE,FileUtil.isModifed(srcFile,DateUtil.date().getTime()));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. normalize(java.lang.String)

Method description

Repair path

If there is a separator at the end of the original path, it will be retained as the standard separator (/), otherwise it will not be retained

  1. 1. Unified use/
  2. 2. Multiple / convert to one/
  3. 3. Remove the spaces on both sides
  4. 4. And Convert to absolute path. When... Is more than the existing path, it will directly return to the root path

Chestnuts:

"/foo//" => "/foo/"
"/foo/./" => "/foo/"
"/foo/.../bar" => "/bar"
"/foo/.../bar/" => "/bar/"
"/foo/.../bar/.../baz" => "/baz"
"/.../" => "/"
"foo/bar/..." => "foo"
"foo/.../bar" => "bar"
"foo/.../.../bar" => "bar"
"//server/foo/.../bar" => "/server/bar"
"//server/.../bar" => "/bar"
"C:\foo\...\bar" => "C:/bar"
"C:\...\bar" => "C:/bar"
"~/foo/.../bar/" => "~/bar/"
"~/.../bar" => "bar"

Supported version and above

Parameter Description:

Parameter name

describe

String path

Path original path

Return value:

Repaired path

Reference case:

		Assert.assertEquals("/foo/", FileUtil.normalize("/foo//"));
		Assert.assertEquals("/foo/", FileUtil.normalize("/foo/./"));
		Assert.assertEquals("/bar", FileUtil.normalize("/foo/../bar"));
		Assert.assertEquals("/bar/", FileUtil.normalize("/foo/../bar/"));
		Assert.assertEquals("/baz", FileUtil.normalize("/foo/../bar/../baz"));
		Assert.assertEquals("/", FileUtil.normalize("/../"));
		Assert.assertEquals("foo", FileUtil.normalize("foo/bar/.."));
		Assert.assertEquals("bar", FileUtil.normalize("foo/../../bar"));
		Assert.assertEquals("bar", FileUtil.normalize("foo/../bar"));
		Assert.assertEquals("/server/bar", FileUtil.normalize("//server/foo/../bar"));
		Assert.assertEquals("/bar", FileUtil.normalize("//server/../bar"));
		Assert.assertEquals("C:/bar", FileUtil.normalize("C:\foo\..\bar"));
		Assert.assertEquals("C:/bar", FileUtil.normalize("C:\..\bar"));
		Assert.assertEquals("bar", FileUtil.normalize("../../bar"));
		Assert.assertEquals("C:/bar", FileUtil.normalize("/C:/bar"));
		Assert.assertEquals("C:", FileUtil.normalize("C:"));

		Assert.assertEquals("\/192.168.1.1/Share/", FileUtil.normalize("\\192.168.1.1\Share\"));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. subPath(java.lang.String, java.io.File)

Method description

Get relative subpath

Chestnuts:

dirPath: d:/aaa/bbb filePath: d:/aaa/bbb/ccc => ccc
dirPath: d:/Aaa/bbb filePath: d:/aaa/bbb/ccc.txt => ccc.txt

Supported version and above

Parameter Description:

Parameter name

describe

String rootDir

rootDir absolute parent path

File file

File file

Return value:

Relative sub path

Reference case:

			String subPath = FileUtil.subPath("d:/aaa/bbb/", new File("d:/aaa/bbb/ccc/"));
		Assert.assertEquals("ccc", subPath);

		subPath = FileUtil.subPath("d:/aaa/bbb", new File("d:/aaa/bbb/ccc/"));
		Assert.assertEquals("ccc", subPath);

		subPath = FileUtil.subPath("d:/aaa/bbb", new File("d:/aaa/bbb/ccc/test.txt"));
		Assert.assertEquals("ccc/test.txt", subPath);

		subPath = FileUtil.subPath("d:/aaa/bbb/", new File("d:/aaa/bbb/ccc"));
		Assert.assertEquals("ccc", subPath);

		subPath = FileUtil.subPath("d:/aaa/bbb", new File("d:/aaa/bbb/ccc"));
		Assert.assertEquals("ccc", subPath);

		subPath = FileUtil.subPath("d:/aaa/bbb", new File("d:/aaa/bbb"));
		Assert.assertEquals("", subPath);

		subPath = FileUtil.subPath("d:/aaa/bbb/", new File("d:/aaa/bbb"));
		Assert.assertEquals("", subPath);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. subPath(java.lang.String, java.lang.String)

Method description

Get relative subpath, ignoring case

Chestnuts:

dirPath: d:/aaa/bbb filePath: d:/aaa/bbb/ccc => ccc
dirPath: d:/Aaa/bbb filePath: d:/aaa/bbb/ccc.txt => ccc.txt
dirPath: d:/Aaa/bbb filePath: d:/aaa/bbb/ => ""

Supported version and above

Parameter Description:

Parameter name

describe

String dirPath

dirPath parent path

String filePath

filePath file path

Return value:

Relative sub path

Reference case:

		String subPath = FileUtil.subPath("d:/aaa/bbb/", "d:/aaa/bbb/ccc/");
		Assert.assertEquals("ccc/", subPath);

		subPath = FileUtil.subPath("d:/aaa/bbb", "d:/aaa/bbb/ccc/");
		Assert.assertEquals("ccc/", subPath);

		subPath = FileUtil.subPath("d:/aaa/bbb", "d:/aaa/bbb/ccc/test.txt");
		Assert.assertEquals("ccc/test.txt", subPath);

		subPath = FileUtil.subPath("d:/aaa/bbb/", "d:/aaa/bbb/ccc");
		Assert.assertEquals("ccc", subPath);

		subPath = FileUtil.subPath("d:/aaa/bbb", "d:/aaa/bbb/ccc");
		Assert.assertEquals("ccc", subPath);

		subPath = FileUtil.subPath("d:/aaa/bbb", "d:/aaa/bbb");
		Assert.assertEquals("", subPath);

		subPath = FileUtil.subPath("d:/aaa/bbb/", "d:/aaa/bbb");
		Assert.assertEquals("", subPath);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. pathEndsWith(java.io.File, java.lang.String)

Method description

Judge whether the file path has a specified suffix, ignoring case

Common phrase judgment extension

Supported version and above

Parameter Description:

Parameter name

describe

File file

file or directory

String suffix

suffix

Return value:

Is there a suffix specified

Reference case:

		File srcFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\copyTest1.txt");
		Assert.assertEquals(Boolean.TRUE, FileUtil.pathEndsWith(srcFile,"txt"));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getType(java.io.File)

Method description

Obtain the file type according to the header information of the file stream

  1,Unrecognized type is recognized by extension by default
  2,xls,doc,msi Header information cannot be distinguished according to extension
  3,zip May be docx,xlsx,pptx,jar,war Header information cannot be distinguished according to extension

Supported version and above

Parameter Description:

Parameter name

describe

File file

File {@ link File}

Return value:

Type, file extension, not found as {@ code null}

Reference case:

		//Obtain the file type according to the header information of the file stream
		File file = FileUtil.file("hutool.jpg");
		String type = FileUtil.getType(file);
		Assert.assertEquals("jpg", type);

		FileTypeUtil.putFileType("ffd8ffe000104a464946", "new_jpg");
		String newType = FileUtil.getType(file);
		Assert.assertEquals("new_jpg", newType);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. convertCharset(java.io.File, java.nio.charset.Charset, java.nio.charset.Charset)

Method description

Convert file code

This method is used to convert the file code. The actual code of the read file must be consistent with the specified srcCharset code, otherwise it will cause garbled code

Supported version and above

3.1.0

Parameter Description:

Parameter name

describe

File file

File file

Charset srcCharset

The encoding of the srcCharset original file must be consistent with the encoding of the file content

Charset destCharset

Encoding after destCharset transcoding

Return value:

Converted encoded file

Reference case:

		File srcFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\copyTest1.txt");
		//Convert file code
		File converFile = FileUtil.convertCharset(srcFile,CharsetUtil.CHARSET_UTF_8,CharsetUtil.CHARSET_GBK);
		InputStream input =  null;
		try {
			//Create stream
			input =  new FileInputStream(srcFile);
			String str = IoUtil.read(input,CharsetUtil.CHARSET_GBK);
			System.out.println(str);
		} catch (IOException e) {
			//Throw a runtime exception (stop the program directly)
			throw new RuntimeException("Runtime exception",e);
		} finally {
			IoUtil.close(input);
		}

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. convertLineSeparator(java.io.File, java.nio.charset.Charset, cn.hutool.core.io.file.LineSeparator)

Method description

Convert line breaks

Converts the newline character of the given file to the specified newline character

Supported version and above

3.1.0

Parameter Description:

Parameter name

describe

File file

File file

Charset charset

charset coding

LineSeparator lineSeparator

lineSeparator linebreak enumeration {@ link LineSeparator}

Return value:

Modified file

Reference case:

		File srcFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\convertLineSeparatorTest.txt");
		File convertLineSeparatorFile =	FileUtil.convertLineSeparator(srcFile, CharsetUtil.CHARSET_UTF_8, LineSeparator.WINDOWS);
		InputStream input =  null;
		try {
			//Create stream
			input =  new FileInputStream(convertLineSeparatorFile);
			String str = IoUtil.read(input,CharsetUtil.CHARSET_UTF_8);
			System.out.println(str);
		} catch (IOException e) {
			//Throw a runtime exception (stop the program directly)
			throw new RuntimeException("Runtime exception",e);
		} finally {
			IoUtil.close(input);
		}

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. cleanInvalid(java.lang.String)

Method description

Clear the illegal characters in the file name that are not supported under Windows, including: /: * "< >|

Supported version and above

3.3.1

Parameter Description:

Parameter name

describe

String fileName

fileName file name (path must not be included, otherwise the path character will be replaced)

Return value:

Cleaned file name

Reference case:

		//Clear the illegal characters in the file name that are not supported under Windows, including: /: *? " < > |
		String fileName = "cleanInvalidTest \ / : * ? " < >  |.txt";
		System.out.println(FileUtil.cleanInvalid(fileName));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. containsInvalid(java.lang.String)

Method description

Whether the file name contains illegal characters that are not supported under Windows, including: /: * "< >|

Supported version and above

3.3.1

Parameter Description:

Parameter name

describe

String fileName

fileName file name (path must not be included, otherwise the path character will be replaced)

Return value:

Contains illegal characters

Reference case:

		String fileName = "cleanInvalidTest \ / : * ? " < >  |.txt";
		//Does the file name contain illegal characters that are not supported under Windows, including: /: *? " < > |
		Assert.assertEquals(Boolean.TRUE, FileUtil.containsInvalid(fileName));
		fileName = "cleanInvalidTest.txt";
		Assert.assertEquals(Boolean.FALSE, FileUtil.containsInvalid(fileName));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. checksumCRC32(java.io.File)

Method description

Calculation file CRC32 check code

Supported version and above

4.0.6

Parameter Description:

Parameter name

describe

File file

file, cannot be directory

Return value:

CRC32 value

Reference case:

		File srcFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\copyTest1.txt");
		System.out.println(FileUtil.checksumCRC32(srcFile));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. checksum(java.io.File, java.util.zip.Checksum)

Method description

Calculation file check code

Supported version and above

4.0.6

Parameter Description:

Parameter name

describe

File file

file, cannot be directory

Checksum checksum

checksum {@link Checksum}

Return value:

Checksum

Reference case:

		File srcFile = FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\copyTest1.txt");
		System.out.println(FileUtil.checksum(srcFile,new CRC32()));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getWebRoot()

Method description

Get the web root path under the Web project

The principle is to obtain the ClassPath path first. Since the ClassPath is located under WEB-INF/classes / in the web project, you can obtain two-level directories upward.

Supported version and above

4.0.13

Parameter Description:

Parameter name

describe

Return value:

web root path

Reference case:

		File webRoot = FileUtil.getWebRoot();
		Assert.assertNotNull(webRoot);
		Assert.assertEquals("hutool-core", webRoot.getName());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getParent(java.lang.String, int)

Method description

Gets the parent path of the specified hierarchy

getParent("d:/aaa/bbb/cc/ddd", 0) -> "d:/aaa/bbb/cc/ddd"
getParent("d:/aaa/bbb/cc/ddd", 2) -> "d:/aaa/bbb"
getParent("d:/aaa/bbb/cc/ddd", 4) -> "d:/"
getParent("d:/aaa/bbb/cc/ddd", 5) -> null

Supported version and above

4.1.2

Parameter Description:

Parameter name

describe

String filePath

filePath directory or file path

int level

Level level

Return value:

The path is File. If it does not exist, null is returned

Reference case:

		// Test only under Windows
		if (FileUtil.isWindows()) {
			String parent = FileUtil.getParent("d:/aaa/bbb/cc/ddd", 0);
			Assert.assertEquals("D:\aaa\bbb\cc\ddd", parent);

			parent = FileUtil.getParent("d:/aaa/bbb/cc/ddd", 1);
			Assert.assertEquals("D:\aaa\bbb\cc", parent);

			parent = FileUtil.getParent("d:/aaa/bbb/cc/ddd", 2);
			Assert.assertEquals("D:\aaa\bbb", parent);

			parent = FileUtil.getParent("d:/aaa/bbb/cc/ddd", 4);
			Assert.assertEquals("D:\", parent);

			parent = FileUtil.getParent("d:/aaa/bbb/cc/ddd", 5);
			Assert.assertNull(parent);

			parent = FileUtil.getParent("d:/aaa/bbb/cc/ddd", 10);
			Assert.assertNull(parent);
		}

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getParent(java.io.File, int)

Method description

Gets the parent path of the specified hierarchy

getParent(file("d:/aaa/bbb/cc/ddd", 0)) -> "d:/aaa/bbb/cc/ddd"
getParent(file("d:/aaa/bbb/cc/ddd", 2)) -> "d:/aaa/bbb"
getParent(file("d:/aaa/bbb/cc/ddd", 4)) -> "d:/"
getParent(file("d:/aaa/bbb/cc/ddd", 5)) -> null

Supported version and above

4.1.2

Parameter Description:

Parameter name

describe

File file

File directory or file

int level

Level level

Return value:

The path is File. If it does not exist, null is returned

Reference case:

		// Test only under Windows
		if (FileUtil.isWindows()) {
			File parent = FileUtil.getParent(FileUtil.file("d:/aaa/bbb/cc/ddd"), 0);
			Assert.assertEquals(FileUtil.file("d:\aaa\bbb\cc\ddd"), parent);

			parent = FileUtil.getParent(FileUtil.file("d:/aaa/bbb/cc/ddd"), 1);
			Assert.assertEquals(FileUtil.file("d:\aaa\bbb\cc"), parent);

			parent = FileUtil.getParent(FileUtil.file("d:/aaa/bbb/cc/ddd"), 2);
			Assert.assertEquals(FileUtil.file("d:\aaa\bbb"), parent);

			parent = FileUtil.getParent(FileUtil.file("d:/aaa/bbb/cc/ddd"), 4);
			Assert.assertEquals(FileUtil.file("d:\"), parent);

			parent = FileUtil.getParent(FileUtil.file("d:/aaa/bbb/cc/ddd"), 5);
			Assert.assertNull(parent);

			parent = FileUtil.getParent(FileUtil.file("d:/aaa/bbb/cc/ddd"), 10);
			Assert.assertNull(parent);
		}

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. checkSlip(java.io.File, java.io.File)

Method description

Check whether the parent full path is the first half of the self path. If not, it indicates that it is not a child path, and there may be slip injection.

see http://blog.nsfocus.net/zip-slip-2/ ###Supported version and above

Parameter Description:

Parameter name

describe

File parentFile

parentFile parent file or directory

File file

File sub file or directory

Return value:

Sub file or directory

Reference case 1:

		//Check whether the parent full path is the first half of the self path. If it is not a child path, there may be slip injection. This method will check the slip vulnerability. See the vulnerability description http://blog.nsfocus.net/zip-slip-2/
		File srcFile = FileUtil.checkSlip(new File("C:\Users\Administrator\Desktop\xuzhu"),new File("C:\Users\Administrator\Desktop\xuzhu\contentEqualsIgnoreEOLTest1.txt"));
		Assert.assertEquals(Boolean.TRUE,srcFile.exists());

Reference case 2:

		//Check whether the parent full path is the first half of the self path. If it is not a child path, there may be slip injection. This method will check the slip vulnerability. See the vulnerability description http://blog.nsfocus.net/zip-slip-2/
		File srcFile = FileUtil.checkSlip(new File("C:\Users\Administrator\Desktop\xuzhu"),new File("contentEqualsIgnoreEOLTest1.txt"));
		//An error will be reported: illegalargumentexception: new file is outside of the parent dir: contentequalsignoreeoltest1 txt
		Assert.assertEquals(Boolean.TRUE,srcFile.exists());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getMimeType(java.lang.String)

Method description

Obtain MimeType based on file extension

Supported version and above

4.1.15

Parameter Description:

Parameter name

describe

String filePath

filePath file path or file name

Return value:

MimeType

Reference case:

		String mimeType = FileUtil.getMimeType("test2Write.jpg");
		Assert.assertEquals("image/jpeg", mimeType);

		mimeType = FileUtil.getMimeType("test2Write.html");
		Assert.assertEquals("text/html", mimeType);

		mimeType = FileUtil.getMimeType("main.css");
		Assert.assertEquals("text/css", mimeType);

		mimeType = FileUtil.getMimeType("test.js");
		Assert.assertEquals("application/x-javascript", mimeType);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. isSymlink(java.io.File)

Method description

Determine whether it is a symbolic link file

Supported version and above

4.4.2

Parameter Description:

Parameter name

describe

File file

File the file being checked

Return value:

Is it a symbolic link file

Reference case:

		String path = "C:\Users\Administrator\Desktop\xuzhu\toCopyTest1.txt";
		//Determine whether it is a symbolic link file
		Assert.assertEquals(Boolean.FALSE, FileUtil.isSymlink(new File(path)));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. isSub(java.io.File, java.io.File)

Method description

Judge whether a given directory is a subdirectory of a given file or folder

Supported version and above

4.5.4

Parameter Description:

Parameter name

describe

File parent

parent directory

File sub

sub subdirectory

Return value:

Is the subdirectory a subdirectory of the parent directory

Reference case:

		File file = new File("d:/test");
		File file2 = new File("d:/test2/aaa");
		Assert.assertFalse(FileUtil.isSub(file, file2));

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. createRandomAccessFile(java.nio.file.Path, cn.hutool.core.io.file.FileMode)

Method description

Create {@ link RandomAccessFile}

Supported version and above

4.5.2

Parameter Description:

Parameter name

describe

Path path

Path file path

FileMode mode

Mode mode, see {@ link FileMode}

Return value:

{@link RandomAccessFile}

Reference case:

		Path path = Paths.get("C:\Users\Administrator\Desktop\xuzhu\toCopyTest1.txt");
		RandomAccessFile randomAccessFile = FileUtil.createRandomAccessFile(path, FileMode.r);
		Assert.assertNotNull(randomAccessFile);

Source code analysis:

Link: to be added
RandomAccessFile analysis
FileMode analysis

Method details

Method name: CN hutool. core. io. FileUtil. createRandomAccessFile(java.io.File, cn.hutool.core.io.file.FileMode)

Method description

Create {@ link RandomAccessFile}

Supported version and above

4.5.2

Parameter Description:

Parameter name

describe

File file

File file

FileMode mode

Mode mode, see {@ link FileMode}

Return value:

{@link RandomAccessFile}

Reference case:

		RandomAccessFile randomAccessFile = FileUtil.createRandomAccessFile(new File("C:\Users\Administrator\Desktop\xuzhu\toCopyTest1.txt"), FileMode.r);
		Assert.assertNotNull(randomAccessFile);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. tail(java.io.File, cn.hutool.core.io.LineHandler)

Method description

The file content follower realizes the function similar to the "tail -f" command under Linux

This method blocks the current thread

Supported version and above

Parameter Description:

Parameter name

describe

File file

File file

LineHandler handler

handler line processor

Return value:

Reference case:

public class IoUtilLineHandler implements LineHandler {
	@Override
	public void handle(String line) {
		System.out.println("handle:"+line);
	}
}
//------------------------
	//Implement the function similar to the "tail -f" command under Linux, but when listening and starting, tocopytest1 Txt file, the customized IoUtilLineHandler will be triggered
		FileUtil.tail(FileUtil.file("C:\Users\Administrator\Desktop\xuzhu\toCopyTest1.txt"), new IoUtilLineHandler());

Before listening start:

After listening is started:

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. tail(java.io.File, java.nio.charset.Charset, cn.hutool.core.io.LineHandler)

Method description

The file content follower realizes the function similar to the "tail -f" command under Linux

This method blocks the current thread

Supported version and above

Parameter Description:

Parameter name

describe

File file

File file

Charset charset

charset coding

LineHandler handler

handler line processor

Return value:

Reference case:

public class IoUtilLineHandler implements LineHandler {
	@Override
	public void handle(String line) {
		System.out.println("handle:"+line);
	}
}
//------------------------
FileUtil.tail(FileUtil.file("e:/tail.txt"), CharsetUtil.CHARSET_UTF_8,new IoUtilLineHandler());

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. tail(java.io.File, java.nio.charset.Charset)

Method description

The file content follower realizes the function similar to the "tail -f" command under Linux

This method blocks the current thread

Supported version and above

Parameter Description:

Parameter name

describe

File file

File file

Charset charset

charset coding

Return value:

Reference case:

//Built in command line processor (printed on the console)
		FileUtil.tail(FileUtil.file("e:/tail.txt"), CharsetUtil.CHARSET_GBK);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getName(java.io.File)

Method description

Return file name

Supported version and above

4.1.13

Parameter Description:

Parameter name

describe

File file

File file

Return value:

file name

Reference case:

		String path = "d:\aaa\bbb\cc\ddd\";
		String name = FileUtil.getName(new File(path));
		Assert.assertEquals("ddd", name);

		path = "d:\aaa\bbb\cc\ddd.jpg";
		name = FileUtil.getName(new File(path));
		Assert.assertEquals("ddd.jpg", name);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getName(java.lang.String)

Method description

Return file name

Supported version and above

4.1.13

Parameter Description:

Parameter name

describe

String filePath

filePath file

Return value:

file name

Reference case:

		String path = "d:\aaa\bbb\cc\ddd\";
		String name = FileUtil.getName(path);
		Assert.assertEquals("ddd", name);

		path = "d:\aaa\bbb\cc\ddd.jpg";
		name = FileUtil.getName(path);
		Assert.assertEquals("ddd.jpg", name);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getSuffix(java.io.File)

Method description

Get the file suffix without "."

Supported version and above

5.3.8

Parameter Description:

Parameter name

describe

File file

File file

Return value:

Extension

Reference case:

		String	path = "d:\aaa\bbb\cc\ddd.jpg";
		//Get the file suffix without "."
		String suffix = FileUtil.getSuffix(new File(path));
		Assert.assertEquals("jpg", suffix);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getSuffix(java.lang.String)

Method description

Get the file suffix without "."

Supported version and above

5.3.8

Parameter Description:

Parameter name

describe

String fileName

fileName filename

Return value:

Extension

Reference case:

		String	path = "d:\aaa\bbb\cc\ddd.jpg";
		//Get the file suffix without "."
		String suffix = FileUtil.getSuffix(path);
		Assert.assertEquals("jpg", suffix);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getPrefix(java.io.File)

Method description

Returns the main file name

Supported version and above

5.3.8

Parameter Description:

Parameter name

describe

File file

File file

Return value:

Master file name

Reference case:

		String	path = "d:\aaa\bbb\cc\ddd.jpg";
		//Returns the main file name
		String suffix = FileUtil.getPrefix(new File(path));
		Assert.assertEquals("ddd", suffix);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getPrefix(java.lang.String)

Method description

Returns the main file name

Supported version and above

5.3.8

Parameter Description:

Parameter name

describe

String fileName

fileName full fileName

Return value:

Master file name

Reference case:

		String	path = "d:\aaa\bbb\cc\ddd.jpg";
		//Returns the main file name
		String suffix = FileUtil.getPrefix(path);
		Assert.assertEquals("ddd", suffix);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. mainName(java.io.File)

Method description

Returns the main file name

Supported version and above

Parameter Description:

Parameter name

describe

File file

File file

Return value:

Master file name

Reference case:

		String path = "d:\aaa\bbb\cc\ddd\";
		String mainName = FileUtil.mainName(new File(path));
		Assert.assertEquals("ddd", mainName);

		path = "d:\aaa\bbb\cc\ddd";
		mainName = FileUtil.mainName(new File(path));
		Assert.assertEquals("ddd", mainName);

		path = "d:\aaa\bbb\cc\ddd.jpg";
		mainName = FileUtil.mainName(new File(path));
		Assert.assertEquals("ddd", mainName);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. mainName(java.lang.String)

Method description

Returns the main file name

Supported version and above

Parameter Description:

Parameter name

describe

String fileName

fileName full fileName

Return value:

Master file name

Reference case:

		String path = "d:\aaa\bbb\cc\ddd\";
		String mainName = FileUtil.mainName(path);
		Assert.assertEquals("ddd", mainName);

		path = "d:\aaa\bbb\cc\ddd";
		mainName = FileUtil.mainName(path);
		Assert.assertEquals("ddd", mainName);

		path = "d:\aaa\bbb\cc\ddd.jpg";
		mainName = FileUtil.mainName(path);
		Assert.assertEquals("ddd", mainName);

Source code analysis:

analysis getPrefix and mainName Differences between
 Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. extName(java.io.File)

Method description

Gets the file extension (suffix) without "."

Supported version and above

Parameter Description:

Parameter name

describe

File file

File file

Return value:

Extension

Reference case:

		String path = "d:\aaa\bbb\cc\ddd\";
		String mainName = FileUtil.extName(new File(path));
		Assert.assertEquals("", mainName);

		path = "d:\aaa\bbb\cc\ddd";
		mainName = FileUtil.extName(new File(path));
		Assert.assertEquals("", mainName);

		path = "d:\aaa\bbb\cc\ddd.jpg";
		mainName = FileUtil.extName(new File(path));
		Assert.assertEquals("jpg", mainName);

Source code analysis:

Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. extName(java.lang.String)

Method description

Get the extension (suffix) of the file without "."

Supported version and above

Parameter Description:

Parameter name

describe

String fileName

fileName filename

Return value:

Extension

Reference case:

		String path = "d:\aaa\bbb\cc\ddd\";
		String mainName = FileUtil.extName(path);
		Assert.assertEquals("", mainName);

		path = "d:\aaa\bbb\cc\ddd";
		mainName = FileUtil.extName(path);
		Assert.assertEquals("", mainName);

		path = "d:\aaa\bbb\cc\ddd.jpg";
		mainName = FileUtil.extName(path);
		Assert.assertEquals("jpg", mainName);

Source code analysis:

analysis extName and getSuffix Differences between
 Link: to be added

Method details

Method name: CN hutool. core. io. FileUtil. getLineSeparator()

Method description

Gets the newline separator of the current system

Windows:

Mac:
Linux:

Supported version and above

4.0.5

Parameter Description:

Parameter name

describe

Return value:

Line feed

Reference case:

		//Gets the newline separator of the current system
		//* Windows: 

		//* Mac: 

		//* Linux: 

		System.out.println("//Get the newline separator of the current system "");
		System.out.println("//* Windows: \r

");
System.out.print(FileUtil.getLineSeparator());
System.out.println("//* Mac: \r");
System.out.print(FileUtil.getLineSeparator());
System.out.println("//* Linux:
");

Source code analysis:

Link: to be added

Topics: Javascript Front-end html