Java Files class was introduced in Java 1.7 and is a part of java.nio.file package.

Java Files类是Java 1.7中引入的,是java.nio.file包的一部分。

(Java Files Class)

  • Java Files class contains static methods that work on files and directories. Java Files类包含可用于文件和目录的静态方法。
  • This class is used for basic file operations like create, read, write, copy and delete the files or directories of the file system.

Before move ahead let’s have a look at the below terms first:

在继续之前,我们先来看一下以下术语:

  1. Path: This is the interface that replaces java.io.File class as the representation of a file or a directory when we work in Java NIO. Path :当我们在Java NIO中工作时,这是一个接口,它将java.io.File类替换为文件或目录的表示形式。
  2. Paths: This class contains a static method to create Path instance. Paths :此类包含创建Path实例的静态方法。

java.nio.file.Path interface is just like the old java.io.File class. Path represents location of the file and when we create a Path to new file, it does not create actual file until we create it using Files.createFile(Path filePath).

As we can see in above diagram, Paths class is used to create instance of Path and Files class uses Path instance to work on a file.

java.nio.file.Path 接口类似于旧的java.io.File类。 Path表示文件的位置,当我们创建新文件的路径时,它只有在使用Files.createFile(Path filePath)创建文件时才创建实际文件。

如上图所示,Paths类用于创建Path的实例,Files类使用Path实例在文件上工作。

File and Path objects know how to convert to the other, that’s how we can use older code to interact with new Files utility.

文件Path对象知道如何转换为其他对象,这就是我们可以使用旧代码与新文件实用程序进行交互的方式。

(Java IO vs NIO)

(How to Create Path)

We can create an object of Path by calling Paths.get(String first, String... more) method of Paths class.

我们可以通过调用Paths类的Paths.get(String first, String... more)方法来创建Path对象。

Path path1 = Paths.get("/tmp/file.txt"); // For UNIX

Path path2 = Paths.get("D:/data/file.txt"); // For Windows

We can also create an object of Path by separating parts of the path in Paths.get() method.

我们还可以通过在Paths.get()方法中分隔Path的各个部分来创建Path的对象。

Path path1 = Paths.get("/tmp", "file.txt");

Path path2 = Paths.get("D:", "data", "file.txt");

Path path3 = Paths.get("D:/data", "file.txt") ;

As we can see, we can pass folder and file name in Paths.get() method separately.

如我们所见,我们可以在Paths.get()方法中分别传递文件夹和文件名。

(Java Files Methods)

Java NIO Files class contains static methods that is used for manipulating files and directories and those methods mostly works on Path object.

Java NIO Files类包含用于处理文件和目录的静态方法,这些方法通常在Path对象上起作用。

Let’s have a look at below methods of Files class:

让我们看一下下面的Files类方法:

  1. copy(InputStream in, Path target, CopyOption… options): This method copies all bytes from specified input stream to specified target file and it returns number of bytes read or written as long value. copy(InputStream输入,路径目标,CopyOption…选项):此方法将所有字节从指定的输入流复制到指定的目标文件,并返回读取或写入的字节数作为long值。
  2. copy(Path source, OutputStream out): This method copies all bytes from specified source file to given output stream and it returns number of bytes read or written as long value. copy(Path source,OutputStream out):此方法将所有字节从指定的源文件复制到给定的输出流,并且将读取或写入的字节数作为long值返回。
  3. copy(Path source, Path target, CopyOption… options): This method copies given source file to specified target file and it returns path of target file. 复制(路径源,路径目标,CopyOption…选项):此方法将给定的源文件复制到指定的目标文件,并返回目标文件的路径。
  4. createDirectories(Path dir, FileAttribute<?>… attrs): This method creates a directories using given path by creating all nonexistent parent directories first. This method will not throw an exception if the directory could not be created because it already exists. FileAttribute is an optional parameter to set automatically when creating the nonexistent directories and it returns the path of created directory. createDirectories(Path dir,FileAttribute <?>…attrs):此方法通过首先创建所有不存在的父目录来使用给定路径创建目录。 如果由于目录已经存在而无法创建目录,则此方法不会引发异常。 FileAttribute是一个可选参数,可在创建不存在的目录时自动设置,并返回创建目录的路径。
  5. createDirectory(Path dir, FileAttribute<?>… attrs): This method creates a directory using given path, if it creates directory successfully it will returns the path of the created directory. If directory is already exists then it will throw nio.file.FileAlreadyExistsException. createDirectory(Path dir,FileAttribute <?>…attrs):此方法使用给定路径创建目录,如果成功创建目录,它将返回已创建目录的路径。 如果目录已经存在,则将抛出nio.file.FileAlreadyExistsException。
  6. createFile(Path path, FileAttribute<?>… attrs): This method creates a new empty file using given path and returns path of newly created file if it creates it successfully. If file is already exists then it will throw nio.file.FileAlreadyExistsException. createFile(Path path,FileAttribute <?>…attrs):此方法使用给定路径创建一个新的空文件,如果成功创建,则返回新创建文件的路径。 如果文件已经存在,则将抛出nio.file.FileAlreadyExistsException。
  7. createTempDirectory(Path dir, String prefix, FileAttribute<?>… attrs): This method creates a Temporary directory using given path and it will generate the name of directory using given prefix. It will return the path of newly created temporary directory. createTempDirectory(路径目录,字符串前缀,FileAttribute <?>…attrs):此方法使用给定的路径创建一个临时目录,并将使用给定的前缀生成目录的名称。 它将返回新创建的临时目录的路径。
  8. createTempDirectory(String prefix, FileAttribute<?>… attrs): This method creates a Temporary directory in the default temporary-file directory and generate the name of directory using given prefix. It will return the path of newly created temporary directory which is associated with the default File System. createTempDirectory(String prefix,FileAttribute <?>…attrs):此方法在默认的临时文件目录中创建一个Temporary目录,并使用给定的前缀生成目录的名称。 它将返回与默认文件系统关联的新创建的临时目录的路径。
  9. createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>… attrs): This method creates a temporary file at specified directory and generates the file name using given prefix and suffix and returns the path of newly created file. createTempFile(路径目录,字符串前缀,字符串后缀,FileAttribute <?>…attrs):此方法在指定目录下创建一个临时文件,并使用给定的前缀和后缀生成文件名,并返回新创建文件的路径。
  10. createTempFile(String prefix, String suffix, FileAttribute<?>… attrs): This method creates a temporary file at default temporary-file directory and generates the file name using given prefix and suffix and returns the path of newly created file. createTempFile(字符串前缀,字符串后缀,FileAttribute <?>…attrs):此方法在默认的临时文件目录中创建一个临时文件,并使用给定的前缀和后缀生成文件名,并返回新创建文件的路径。
  11. delete(Path path): This is a void method and simply deletes the file from specified path. This method throws NoSuchFileException if the file is not exists at specified path and if the file is directory and it may not empty and cannot be deleted, in this case it will throws delete(Path path):这是一个void方法,只是从指定路径中删除文件。 如果该文件在指定路径下不存在,并且该文件是目录,并且该文件可能不为空并且无法删除,则此方法将引发NoSuchFileException。
  12. deleteIfExists(Path path): This methods checks if file exists before delete the file and returns boolean value true if the file at the given path gets deleted successfully and returns false if the file is not exists at given path. If the file is directory and it may not empty and cannot be deleted, in this case it will throws deleteIfExists(Path path):此方法在删除文件之前检查文件是否存在,如果在给定路径下的文件被成功删除,则返回布尔值true;如果在给定路径下不存在文件,则返回false。 如果文件是目录,并且它可能不为空并且无法删除,则在这种情况下它将抛出
  13. exists(Path path): This method checks if file exists at specified path and if the file exists it will return true or else it returns false. exist(Path path):此方法检查文件是否在指定的路径处存在,并且如果文件存在,它将返回true,否则返回false。
  14. getLastModifiedTime(Path path, Linkoption… options): This method returns a file’s last modified time from given path as getLastModifiedTime(Path path,Linkoption…options):此方法从给定路径返回文件的上次修改时间,如下所示:
  15. getOwner(Path path, Linkoption… options): This method returns UserPrincipal representing the owner of the file at given path. getOwner(Path path,Linkoption…options):此方法返回UserPrincipal,它表示给定路径下文件的所有者。
  16. isDirectory(Path path, Linkoption… options): This method checks if the file is a directory from given path. It returns true if the file is directory and false if the file does not exists or is not a directory or it cannot be determined if the file is a directory or not. isDirectory(路径路径,Linkoption…选项):此方法检查文件是否为给定路径中的目录。 如果该文件是目录,则返回true;如果该文件不存在或不是目录,则返回false;或者,如果该文件不是目录,则返回false。
  17. isExecutable(Path path): This method checks whether file at given path is executable or not and it also checks that file exists and that this JVM has appropriate privilege to execute the file. It returns true if the file is exists at given path and is executable and false if the file does not exists or JVM has not sufficient privilege to execute file or access cannot be determined. isExecutable(Path path):此方法检查给定路径上的文件是否可执行,还检查文件是否存在以及此JVM具有执行该文件的适当特权。 如果文件存在于给定的路径并且可以执行,则返回true;如果文件不存在或者JVM没有足够的特权执行文件或无法确定访问,则返回false。
  18. isHidden(Path path): This method tells whether file at given is considered as hidden or not. The exact definition of hidden is platform or provider dependent. In case of UNIX system a file is considered hidden if the name of file is starts with period character (‘.’) And in case of WINDOWS file is considered as hidden if it is not a directory and DOS hidden attribute is set. It returns true if the file at given path is considered as hidden or else false. isHidden(Path path):此方法指示给定文件是否被视为隐藏。 隐藏的确切定义取决于平台或提供者。 在UNIX系统中,如果文件名以句点字符('。'开头),则该文件被认为是隐藏的;在WINDOWS文件中,如果该文件不是目录并且设置了DOS hidden属性,则该文件被认为是隐藏的。 如果将给定路径下的文件视为隐藏文件,则返回true,否则返回false。
  19. isReadable(Path path): This method tests whether the file at given path is readable or not. It reruns true if the file at specified path exists and is readable and false if the file does not exists or read access is denied because JVM does not has sufficient privilege or access cannot be determined. isReadable(Path path):此方法测试给定路径下的文件是否可读。 如果指定路径上的文件存在并且可读,则重新运行true;如果文件不存在,则重新运行false;或者由于JVM没有足够的特权或无法确定访问而拒绝读取访问。
  20. isWritable(Path path): This method tests whether the file at given path is writable or not. It reruns true if the file at specified path exists and is writable and false if the file does not exists or write access is denied because JVM does not has sufficient privilege or access cannot be determined. isWritable(Path path):此方法测试给定路径处的文件是否可写。 如果指定路径上的文件存在并且可写,则重新运行true;如果文件不存在或由于JVM没有足够的特权或无法确定访问而拒绝写访问,则重新运行false。
  21. move(Path source, Path target, CopyOption… options): This method move or rename a source file to target file and returns the path of target file. Option parameter may include following :
    REPLACE_EXISTING: It means if the target file exists then replaces it if it is not a non-empty directory.ATOMIC_MOVE: It means move is performed as atomic file system operation and all other options are ignored.
    This method throws FileAleadyExistsException if the target file exists but cannot be replaced because the REPLACE_EXISTING option is not specified.
    This method throws DirectoryNotEmptyException if REPlACE_EXISTING option is specified but the file cannot be replaced because it is a non-empty directory.move(路径源,路径目标,CopyOption…选项):此方法将源文件移动或重命名为目标文件,并返回目标文件的路径。 选项参数可能包括以下内容:
    REPLACE_EXISTING:这意味着目标文件是否存在,如果它不是非空目录,则将其替换。 ATOMIC_MOVE:这意味着移动是作为原子文件系统操作执行的,所有其他选项都将被忽略。
    如果目标文件存在,但由于未指定REPLACE_EXISTING选项而无法替换,则此方法将引发FileAleadyExistsException
    如果指定了REPlACE_EXISTING选项,则此方法将抛出DirectoryNotEmptyException ,但是由于该文件是非空目录,因此无法替换。
  22. newBufferedReader(Path path, Charset cs): This method opens a file using given path for reading by returning a BufferedReader that used to read text from the file.Bytes from the file are decoded into characters using the specified charset. newBufferedReader(Path path,Charset cs):此方法通过返回用于读取文件文本的BufferedReader使用给定的路径打开文件以进行读取。使用指定的字符集将文件中的字节解码为字符。
  23. newBufferedWriter(Path path, Charset cs, Openoption… options): This method opens or creates a file using given path for writing by returning BufferedWriter that used to write text to the file. The options parameter specifies how the file is created or opened. If no option is specified then it consider CREATE, TRUNCATE_EXISTING and WRITE options by default, this means it opens the file for writing and creates if the file does not exist or truncate existing file to size of 0 if it exists. This method throws UnsupportedOperationException if unsupported option is specified. newBufferedWriter(路径,Charset cs,Openoption…选项):此方法通过返回用于将文本写入文件的BufferedWriter,使用给定的写入路径打开或创建文件。 options参数指定如何创建或打开文件。 如果未指定任何选项,则默认情况下会考虑CREATE,TRUNCATE_EXISTINGWRITE选项,这意味着它将打开要写入的文件并创建文件是否不存在,或者将现有文件截断为0(如果存在)。 如果指定了支持的选项,则此方法将引发UnsupportedOperationException
  24. newByteChannel(Path path, OpenOption… options): This method creates or opens the file using specified path by returning a seekable byte channel to access the file. This method throws UnsupportedOperationException if unsupported option is specified. newByteChannel(路径路径,OpenOption…选项):此方法通过返回可搜索的字节通道来访问文件,从而使用指定的路径创建或打开文件。 如果指定了支持的选项,则此方法将引发UnsupportedOperationException
  25. newDirectoryStream(Path path): This method opens a directory by returning a DirectoryStream to iterate over all entries in the directory from the specified path. The elements return by DirectoryStream’s iterator are of type Path and each one represents an entry in the directory. This method throws NotDirectoryException if the file at given path could not be opened because it is not a directory. newDirectoryStream(Path path):此方法通过返回DirectoryStream来从指定路径遍历目录中的所有条目来打开目录。 DirectoryStream的迭代器返回的元素的类型为Path,每个元素代表目录中的一项。 如果由于给定路径下的文件不是目录而无法打开,则此方法将引发NotDirectoryException
  26. newDirectoryStream(Path path, Filter<? super Path > filter): This method opens a directory by returning a DirectoryStream to iterate over all entries in the directory from the specified path. The elements return by DirectoryStream’s iterator are of type Path and each one represents an entry in the directory and these entries are filtered by the specified filter. This method throws NotDirectoryException if the file at given path could not be opened because it is not a directory. newDirectoryStream(路径路径,Filter <?超级路径>过滤器):此方法通过返回DirectoryStream来从指定路径遍历目录中的所有条目来打开目录。 DirectoryStream的迭代器返回的元素的类型为Path,每个元素都代表目录中的一个条目,并且这些条目由指定的过滤器过滤。 如果由于给定路径下的文件不是目录而无法打开,则此方法将引发NotDirectoryException
  27. newDirectoryStream(Path path, String glob): This method opens a directory by returning a DirectoryStream to iterate over all entries in the directory from the specified path. The elements return by DirectoryStream’s iterator are of type Path and each one represents an entry in the directory and these entries is filtered by matching the String representation of their file names against the specified globbing pattern. This method throws NotDirectoryException if the file at given path could not be opened because it is not a directory and PatternSyntaxException if the pattern is invalid. newDirectoryStream(Path path,String glob):此方法通过返回DirectoryStream以从指定路径遍历目录中的所有条目来打开目录。 DirectoryStream的迭代器返回的元素的类型为Path,每个元素代表目录中的一项,并且通过将其文件名的String表示与指定的glob模式匹配来过滤这些项。 如果由于给定路径下的文件不是目录而无法打开该方法,则抛出NotDirectoryException;如果模式无效,则抛出PatternSyntaxException
  28. newInputStream(Path path, Openoption… options): This method opens a file by returning input stream to read the file from specified path. The options parameter is determines how the file is opened and if no options are specified then it opens the file with READ This method throws IllegalArgumentException if an invalid combination of options is specified and UnsupportedOperationException if an unsupported option is specified. newInputStream(路径路径,Openoption…选项):此方法通过返回输入流以从指定路径读取文件来打开文件。 options参数确定打开文件的方式,如果未指定选项,则使用READ打开文件。如果指定了无效的选项组合,则此方法引发IllegalArgumentException;如果指定了不受支持的选项,则引发UnsupportedOperationException
  29. newOutputStream(Path path, Openoption… options): This method opens a file by returning output stream to write bytes to the file at specified path. The options parameter is determines how the file is opened and If no option is specified then it consider CREATE, TRUNCATE_EXISTING and WRITE options by default, this means it opens the file for writing and creates if the file does not exist or truncate existing file to size of 0 if it exists. This method throws IllegalArgumentException if an invalid combination of options is specified and UnsupportedOperationException if an unsupported option is specified. newOutputStream(路径路径,Openoption…选项):此方法通过返回输出流以将字节写入指定路径的文件来打开文件。 options参数确定打开文件的方式,如果未指定任何选项,则默认情况下考虑CREATE,TRUNCATE_EXISTINGWRITE选项,这意味着它将打开文件进行写入并创建文件是否不存在或将现有文件截断成大小如果存在,则为0。 如果指定了无效的选项组合,则此方法引发IllegalArgumentException;如果指定了不受支持的选项,则引发UnsupportedOperationException
  30. notExists(Path path, LinkOption options): This method tests whether the file at specified path does not exists. The options parameter is used to indicate how symbolic links are handled if the file is symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINK is present then symbolic links are not followed. This method returns true if file does not exist at specified path and false if the file exists or if its existence cannot be determined. notExists(路径,LinkOption选项):此方法测试指定路径处的文件是否不存在。 options参数用于指示如果文件是符号链接,则如何处理符号链接。 默认情况下,遵循符号链接。 如果存在选项NOFOLLOW_LINK ,则不遵循符号链接。 如果文件在指定路径不存在,则此方法返回true;如果文件存在或无法确定其存在,则返回false。
  31. readAllBytes(Path path): This method reads all the bytes from the file at given path and returns the byte array containing the bytes read from the file. readAllBytes(Path path):此方法从给定路径中的文件读取所有字节,并返回包含从文件读取的字节的字节数组。
  32. readAllLines(Path path, Charset cs): This method read all lines from the file at given path and returns the List containing the lines from the file. readAllLines(Path path,Charset cs):此方法从给定路径的文件中读取所有行,并返回包含文件中的行的List
  33. size(Path path): This method returns the size of the file at specified path in bytes. size(Path path):此方法返回指定路径上文件的大小(以字节为单位)。
  34. walkFileTree(Path start, FileVisitor<? Super Path> visitor): This method used to traverse the directory. It traverses the directory at specified path recursively and returns the starting file. walkFileTree(路径开始,FileVisitor <?Super Path>访问者):此方法用于遍历目录。 它以递归方式遍历目录中的指定路径,并返回起始文件。
  35. write(Path path, byte[] bytes, OpenOption… options): This method writes bytes to a file at specified path. The options parameter specifies how the file is created or opened. If no option is specified then it consider CREATE, TRUNCATE_EXISTING and WRITE options by default, this means it opens the file for writing and creates if the file does not exist or truncate existing file to size of 0 if it exists. All the bytes in byte array are written to the file. This method ensures that the file is closed when all the bytes have been written and returns the path of written file. write(路径,byte []个字节,OpenOption…选项):此方法将字节写入指定路径的文件。 options参数指定如何创建或打开文件。 如果未指定任何选项,则默认情况下会考虑CREATE,TRUNCATE_EXISTINGWRITE选项,这意味着它将打开要写入的文件并创建文件是否不存在,或者将现有文件截断为0(如果存在)。 字节数组中的所有字节均写入文件。 此方法可确保在写入所有字节后关闭文件,并返回写入文件的路径。

(Create file Using Files Class)

Files class provides createFile(Path filePath, FileAttribute<?>… attrs) method to create file using specified Path.

Files类提供createFile(Path filePath, FileAttribute<?>… attrs)方法来使用指定的Path创建文件。

Let’s have a look at the below example program.

让我们看一下下面的示例程序。

package com.journaldev.examples;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Java Create file using Files class
 * 
 * @author pankaj
 *
 */
public class FilesCreateFileExample {

	public static void main(String[] args) {
		
		//initialize Path object
		Path path = Paths.get("D:/data/file.txt");
		//create file
		try {
			Path createdFilePath = Files.createFile(path);
			System.out.println("File Created at Path : "+createdFilePath);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output of the above program is below:

上面程序的输出如下:

File Created at Path : D:\data\file.txt

(Create Directories Using Files Class)

Files class provides createDirectory(Path dir, FileAttribute<?>… attrs) and createDirectories(Path dir, FileAttribute<?>… attrs) methods to create single and multi level directories using specified Path.

Files类提供createDirectory(Path dir, FileAttribute<?>… attrs)createDirectories(Path dir, FileAttribute<?>… attrs)方法来使用指定的Path创建单级和多级目录。

Let’s have a look at the below example program.

让我们看一下下面的示例程序。

package com.journaldev.examples;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Java Create directories using Files class
 * 
 * @author pankaj
 *
 */
public class FilesCreateDirectoriesExample {

	public static void main(String[] args) {
		// initialize Path objects
		Path path1 = Paths.get("D:/pankaj");
		Path path2 = Paths.get("D:/pankaj/java7");
		Path path3 = Paths.get("D:/pankaj/java7/Files");
		
		try {
			Path createdDir1 = Files.createDirectory(path1);//first level directory
			Path createdDir2 = Files.createDirectory(path2);//second level directory
			Path createdDir3 = Files.createDirectory(path3);//all level directories
			System.out.println("First Level Directory Created at Path : "+createdDir1);
			System.out.println("Second Level Directory Created at Path : "+createdDir2);
			System.out.println("All Level Directories Created at Path : "+createdDir3);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output of the above program is below:

上面程序的输出如下:

First Level Directory Created at Path : D:\pankaj
Second Level Directory Created at Path : D:\pankaj\java7
All Level Directories Created at Path : D:\pankaj\java7\Files

(Convert File to Path and Vice Versa)

File and Path objects can be converted to each other using below methods:

可以使用以下方法将文件和路径对象彼此转换:

File file = new File(“D:/data/file.txt”);

Path path = file.toPath();

File file1 = path.toFile();

(Read File Data using Files Class)

Files class provides following methods for reading file.

Files类提供以下读取文件的方法。

  1. readAllBytes(Path path): This method reads all the bytes from the file at given path and returns the byte array containing the bytes read from the file. readAllBytes(Path path) :此方法从给定路径的文件中读取所有字节,并返回包含从文件中读取的字节的字节数组。
  2. readAllLines(Path path,Charsetcs): This method read all lines from the file at given path and returns the List containing the lines from the file. readAllLines(Path path,Charsetcs) :此方法从给定路径的文件中读取所有行,并返回包含文件中的行的List

Let’s have a look at the below example program.

让我们看一下下面的示例程序。


package com.journaldev.examples;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * Java Files read file example
 * 
 * @author pankaj
 *
 */
public class FilesReadFileExample {

	public static void main(String[] args) {
		
		Path path = Paths.get("D:/data/file.txt");
		try {
			byte[] bs = Files.readAllBytes(path);
			List<String> strings = Files.readAllLines(path);
			
			System.out.println("Read bytes: \n"+new String(bs));
			System.out.println("Read lines: \n"+strings);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Output of above program is below:

上面程序的输出如下:

Read bytes: 
Hello world
This is Read file example
Thank you
Read lines: 
[Hello world, This is Read file example, Thank you]

(Copy File using Files Class)

Files class provide copy(Path source, Path target, CopyOption… options) methodthat copies given source file to specified target file and it returns path of target file.

Files类提供了copy(Path source, Path target, CopyOption… options)方法,该方法将给定的源文件复制到指定的目标文件,并返回目标文件的路径。

Let’s have a look at the below example program:

让我们看下面的示例程序:

package com.journaldev.examples;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * Java Files copy file example
 * 
 * @author pankaj
 *
 */
public class FilesCopyFileExample {

	public static void main(String[] args) {
		Path sourcePath = Paths.get("D:/data/sourceFile.txt");
		Path targetPath = Paths.get("D:/data/targetFile.txt");
		
		try {
			Path path = Files.copy(sourcePath, targetPath,StandardCopyOption.REPLACE_EXISTING);//copy with REPLACE_EXISTING option
			System.out.println("Target file Path : "+path);
			System.out.println("Copied Content : \n"+new String(Files.readAllBytes(path)));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

Output of above program is below:

上面程序的输出如下:

Target file Path : D:\data\targetFile.txt
Copied Content : 
Hello world
This is Copy file example
Thank you

(Move File using Files Class)

Java Files class provides move(Path source, Path target, CopyOption… options) method that move or rename a source file to target file and returns the path of target file.

Java Files类提供了move(Path source, Path target, CopyOption… options)方法,该方法将源文件移动或重命名为目标文件并返回目标文件的路径。

Option parameter may include following:

选项参数可以包括:

REPLACE_EXISTING: It means if the target file exists then replaces it if it is not a non-empty directory.

REPLACE_EXISTING:这意味着目标文件是否存在,如果它不是非空目录,则将其替换。

ATOMIC_MOVE: It means move is performed as atomic file system operation and all other options are ignored.

ATOMIC_MOVE:这意味着移动是作为原子文件系统操作执行的,所有其他选项都将被忽略。

This method throws FileAleadyExistsException if the target file exists but cannot be replaced because the REPLACE_EXISTING option is not specified.

如果目标文件存在,但由于未指定REPLACE_EXISTING选项而无法替换,则此方法将引发FileAleadyExistsException

This method throws DirectoryNotEmptyException if REPlACE_EXISTING option is specified but the file cannot be replaced because it is a non-empty directory.

如果指定了REPlACE_EXISTING选项,则此方法将抛出DirectoryNotEmptyException ,但是由于该文件是非空目录,因此无法替换。

Let’s have a look at the below example program:

让我们看下面的示例程序:

package com.journaldev.examples;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * Java Files move file example
 * 
 * @author pankaj
 *
 */
public class FilesMoveFileExample {

	public static void main(String[] args) {
		Path sourcePath = Paths.get("D:/data/sourceFile.txt");
		Path targetPath = Paths.get("D:/data/targetFile.txt");
		try {
			Path path = Files.move(sourcePath, targetPath,StandardCopyOption.REPLACE_EXISTING);//move with REPLACE_EXISTING option
			System.out.println("Target file Path : "+path);
			System.out.println("Moved Content : \n"+new String(Files.readAllBytes(path)));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

(Write File using Files Class)

Java NIO Files class provides write(Path path, byte[] bytes, OpenOption… options) method that writes bytes to a file at specified path.

Java NIO Files类提供了write(Path path, byte[] bytes, OpenOption… options)方法,该方法将字节写入指定路径的文件。

The options parameter specifies how the file is created or opened. If no option is specified then it consider CREATE, TRUNCATE_EXISTING and WRITE options by default. This means it opens the file for writing and creates if the file does not exist or truncate existing file to size of 0 if it exists.

options参数指定如何创建或打开文件。 如果未指定任何选项,则默认情况下会考虑CREATE,TRUNCATE_EXISTINGWRITE选项。 这意味着它将打开要写入的文件,并创建不存在的文件,如果存在则将其截断为0。

All the bytes in byte array are written to the file. This method ensures that the file is closed when all the bytes have been written and returns the path of written file.

字节数组中的所有字节均写入文件。 此方法可确保在写入所有字节后关闭文件,并返回写入文件的路径。

package com.journaldev.examples;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Java Files write file example
 * 
 * @author pankaj
 *
 */
public class FilesWriteFileExample {

	public static void main(String[] args) {
		Path path = Paths.get("D:/data/test.txt");
		try {
			String str = "This is write file Example";
			byte[] bs = str.getBytes();
			Path writtenFilePath = Files.write(path, bs);
			System.out.println("Written content in file:\n"+ new String(Files.readAllBytes(writtenFilePath)));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

(Walk File Tree)

Files class provides walkFileTree(Path start, FileVisitor<? Super Path> visitor) method that is used to traverse the directory. It traverses the directory at specified path recursively and returns the starting file.

Files类提供了用于遍历目录的walkFileTree(Path start,FileVisitor <?Super Path> visitor)方法。 它以递归方式遍历目录中的指定路径,并返回起始文件。

package com.journaldev.examples;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * Java Files walk file tree example
 * 
 * @author pankaj
 *
 */
public class FilesWalkFileTreeExample {

	public static void main(String[] args) {
		Path path = Paths.get("D:/pankaj");
		try {
			Files.walkFileTree(path, new FileVisitor<Path>() {

				@Override
				public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
					System.out.println("Post Visit Directory: "+dir);
					return FileVisitResult.CONTINUE;
				}

				@Override
				public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
					System.out.println("Pre Visit Directory: "+dir);
					return FileVisitResult.CONTINUE;
				}

				@Override
				public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
					System.out.println("Visit File: "+file);
					return FileVisitResult.CONTINUE;
				}

				@Override
				public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
					System.out.println("Visit Failed File: "+file);
					return FileVisitResult.CONTINUE;
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

Output of above program is below:

上面程序的输出如下:

Pre Visit Directory: D:\pankaj
Pre Visit Directory: D:\pankaj\java6
Pre Visit Directory: D:\pankaj\java6\Files
Visit File: D:\pankaj\java6\Files\file.txt.txt
Post Visit Directory: D:\pankaj\java6\Files
Post Visit Directory: D:\pankaj\java6
Pre Visit Directory: D:\pankaj\java7
Pre Visit Directory: D:\pankaj\java7\Files
Visit File: D:\pankaj\java7\Files\file.txt.txt
Post Visit Directory: D:\pankaj\java7\Files
Post Visit Directory: D:\pankaj\java7
Pre Visit Directory: D:\pankaj\java8
Pre Visit Directory: D:\pankaj\java8\Files
Visit File: D:\pankaj\java8\Files\file.txt.txt
Post Visit Directory: D:\pankaj\java8\Files
Post Visit Directory: D:\pankaj\java8
Post Visit Directory: D:\pankaj

Notice that all the files and folders are processed recursively. This is very useful when you want to do some common processing on all the files, such as rename all the files in a directory recursively.

请注意,所有文件和文件夹都是递归处理的。 当您要对所有文件进行一些通用处理时,例如递归重命名目录中的所有文件,这非常有用。

That’s all for Java Files class.

这就是Java Files类的全部内容。

Reference: API Doc