Java 文件 - java.nio.file.Files 类
Java Files 类是在 Java 1.7 中引入的,是包的一部分java.nio.file
。
Java 文件类
- Java Files 类包含对文件和目录起作用的静态方法。
- 此类用于基本文件操作,如创建、读取、写入、复制和删除文件系统的文件或目录。
在继续之前,我们先看一下以下术语:
Path
java.io.File
:这是在Java NIO中工作时替换类作为文件或目录的表示的接口。- Paths:此类包含一个用于创建
Path
实例的静态方法。
java.nio.file.Path
接口就像旧java.io.File
类一样。Path
表示文件的位置,当我们创建新文件的路径时,它不会创建实际文件,直到我们使用创建它Files.createFile(Path filePath)
。正如我们在上图中所看到的,Paths 类用于创建 Path 的实例,而 Files 类使用 Path 实例来处理文件。文件和对象知道如何转换为另一个,这就是我们如何使用旧代码与新FilesPath
实用程序进行交互的方式。
Java IO 与 NIO
如何创建路径
Path
我们可以通过调用类Paths.get(String first, String... more)
的方法来创建一个对象Paths
。
Path path1 = Paths.get("/tmp/file.txt"); // For UNIX
Path path2 = Paths.get("D:/data/file.txt"); // For Windows
我们还可以通过在方法Path
中分离路径的各个部分来创建一个对象。Paths.get()
Path path1 = Paths.get("/tmp", "file.txt");
Path path2 = Paths.get("D:", "data", "file.txt");
Path path3 = Paths.get("D:/data", "file.txt") ;
如我们所见,我们可以在Paths.get()
方法中分别传递文件夹和文件名。
Java 文件方法
Java NIO Files 类包含用于操作文件和目录的静态方法,这些方法主要作用于Path
对象。让我们看看 Files 类的以下方法:
- copy(InputStream in,Path target,CopyOption… options):此方法将所有字节从指定输入流复制到指定目标文件,并以长值形式返回读取或写入的字节数。
- copy(Path source,OutputStream out):此方法从指定源文件复制所有字节到给定的输出流,并以长值形式返回读取或写入的字节数。
- copy(Path source,Path target,CopyOption... options):此方法将给定的源文件复制到指定的目标文件并返回目标文件的路径。
- createDirectories(Path dir, FileAttribute<?>… attrs):此方法通过首先创建所有不存在的父目录,使用给定路径创建目录。如果目录已存在而无法创建,则此方法不会引发异常。FileAttribute 是创建不存在目录时自动设置的可选参数,它返回已创建目录的路径。
- 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.
- 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.
- 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(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.
- 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(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.
- 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
- 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
- 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.
- getLastModifiedTime(Path path, Linkoption… options): This method returns a file’s last modified time from given path as
- getOwner(Path path, Linkoption… options): This method returns UserPrincipal representing the owner of the file at given path.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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, 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(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.
- 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.
- 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.
- 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.
- 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.
- 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.
- size(Path path): This method returns the size of the file at specified path in bytes.
- 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.
- 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.
Create file Using Files Class
Files class provides createFile(Path filePath, FileAttribute<?>… attrs)
method to create file using specified 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
. 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.
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.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.
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. 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. 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. 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. 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.
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.
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. Reference: API Doc