15.10 Java7的NIO.2 15.10.1 Path Paths和Files核心API

15.10 Java7的NIO.2

Java7对原有的NIO进行了重大改进,改进主要包括如下两方面的内容。

  • 提供了全面的文件IO和文件系统访问支持。
  • 基于异步ChannelIO

第一个改进表现为Java7新增的java.nio.file包及各个子包;
第二个改进表现为Java7java.nio.channels包下增加了多个以Asynchronous开头的Channel接口和类。Java7把这种改进称为NIO.2,本章先详细介绍NIO的第二个改进。

15.1.0.1 Path Paths和Files核心API

早期的Java只提供了一个File类来访问文件系统,但File类的功能比较有限,它不能利用特定文件系统的特性,File所提供的方法的性能也不高。而且,其大多数方法在出错时仅返回失败,并不会提供异常信息

Path接口

NIO.2为了弥补这种不足,引入了一个Path接口,Path接口代表一个平台无关的平台路径

Path接口方法

方法 描述
Path getRoot() Returns the root component of this path as a Path object, or null if this path does not have a root component.
Path toAbsolutePath() Returns a Path object representing the absolute path of this path.
Path getName(int index) Returns a name element of this path as a Path object.
int getNameCount() 返回Path路径所包含的路径名的数量,例如g:\publishl\codes调用该方法就会返回3。

工具类

除此之外,NIO.2还提供了FilesPaths两个工具类,其中

  • Files包含了大量静态的工具方法来操作文件;
  • Paths则包含了两个返回Path的静态工厂方法。

工具类命名规则

FilesPaths两个工具类非常符合Java一贯的命名风格,比如前面介绍的操作数组的工具类为Arrays,操作集合的工具类为Collections,这种一致的命名风格可以让读者快速了解这些工具类的用途。

Paths工具类方法

Paths接口方法 描述
static Path get(String first, String... more) Converts a path string, or a sequence of strings that when joined form a path string, to a Path.
static Path get(URI uri) Converts the given URI to a Path object.

第一个get方法会将给定的多个字符串连缀成路径,比如Paths.get("g:","publish","codes")就返回g:\publish\codes路径。

程序 Path接口Paths工具类示例

下面程序简单示范了Path接口的功能和用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathTest {
public static void main(String[] args) throws Exception {
// 以当前路径来创建Path对象
Path path = Paths.get(".");
System.out.println("path里包含的路径数量:" + path.getNameCount());
System.out.println("path的根路径:" + path.getRoot());
// 获取path对应的绝对路径。
Path absolutePath = path.toAbsolutePath();
System.out.println(absolutePath);
// 获取绝对路径的根路径
System.out.println("absolutePath的根路径:" + absolutePath.getRoot());
// 获取绝对路径所包含的路径数量
System.out.println("absolutePath里包含的路径数量:" + absolutePath.getNameCount());
System.out.println(absolutePath.getName(3));
// 以多个String来构建Path对象
Path path2 = Paths.get("g:", "publish", "codes");
System.out.println(path2);
}
}

Files工具类

Files类是一个高度封装的工具类,它提供了大量的工具方法来完成文件复制读取文件内容写入文件内容等功能,这些原本需要程序员通过IO操作才能完成的功能,现在Files类只要一个工具方法即可。读者应该熟练掌握Files工具类的用法,它所包含的工具方法可以大大地简化文件IO

流操作

Java8进一步增强了Files工具类的功能,允许开发者使用Stream API来操作文件目录和文件内容。

copy方法

方法 描述
static long copy(InputStream in, Path target, CopyOption... options) Copies all bytes from an input stream to a file.
static long copy(Path source, OutputStream out) Copies all bytes from a file to an output stream.
static Path copy(Path source, Path target, CopyOption... options) Copy a file to a target file.

判断方法

是否可读可写可执行

方法 描述
static boolean isReadable(Path path) Tests whether a file is readable.
static boolean isWritable(Path path) Tests whether a file is writable.
static boolean isExecutable(Path path) Tests whether a file is executable.

是否隐藏 是否符号链接

方法 描述
static boolean isHidden(Path path) Tells whether or not a file is considered hidden.
static boolean isSymbolicLink(Path path) Tests whether a file is a symbolic link.

是否文件 是否目录 是否同一个文件

方法 描述
static boolean isDirectory(Path path, LinkOption... options) Tests whether a file is a directory.
static boolean isRegularFile(Path path, LinkOption... options) Tests whether a file is a regular file with opaque content.
static boolean isSameFile(Path path, Path path2) Tests if two paths locate the same file.

是否存在

方法 描述
static boolean exists(Path path, LinkOption... options) Tests whether a file exists.
static boolean notExists(Path path, LinkOption... options) Tests whether the file located by this path does not exist.

read方法

得到字节数组

方法 描述
static byte[] readAllBytes(Path path) Reads all the bytes from a file.

得到字符串

方法 描述
static String readString(Path path) Reads all content from a file into a string, decoding from bytes to characters using the UTF-8 charset.
static String readString(Path path, Charset cs) Reads all characters from a file into a string, decoding from bytes to characters using the specified charset.

得到所有行

方法 描述
static List<String> readAllLines(Path path) Read all lines from a file.
static List<String> readAllLines(Path path, Charset cs) Read all lines from a file.

得到其他

方法 描述
static <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options) Reads a file’s attributes as a bulk operation.
static Map<String,​Object> readAttributes(Path path, String attributes, LinkOption... options) Reads a set of file attributes as a bulk operation.
static Path readSymbolicLink(Path link) Reads the target of a symbolic link (optional operation).

create方法

创建目录

方法 描述
static Path createDirectories(Path dir, FileAttribute<?>... attrs) Creates a directory by creating all nonexistent parent directories first.
static Path createDirectory(Path dir, FileAttribute<?>... attrs) Creates a new directory.

创建文件

方法 描述
static Path createFile(Path path, FileAttribute<?>... attrs) Creates a new and empty file, failing if the file already exists.

创建链接

方法 描述
static Path createLink(Path link, Path existing) Creates a new link (directory entry) for an existing file (optional operation).
static Path createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs) Creates a symbolic link to a target (optional operation).

创建临时目录

方法 描述
static Path createTempDirectory(String prefix, FileAttribute<?>... attrs) Creates a new directory in the default temporary-file directory, using the given prefix to generate its name.
static Path createTempDirectory(Path dir, String prefix, FileAttribute<?>... attrs) Creates a new directory in the specified directory, using the given prefix to generate its name.

创建临时文件

方法 描述
static Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs) Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.
static Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs) Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name.

delete方法

方法 描述
static void delete(Path path) Deletes a file.
static boolean deleteIfExists(Path path) Deletes a file if it exists.

set方法

方法 描述
static Path setAttribute(Path path, String attribute, Object value, LinkOption... options) Sets the value of a file attribute.
static Path setLastModifiedTime(Path path, FileTime time) Updates a file’s last modified time attribute.
static Path setOwner(Path path, UserPrincipal owner) Updates the file owner.
static Path setPosixFilePermissions(Path path, Set<PosixFilePermission> perms) Sets a file’s POSIX permissions.

get方法

方法 描述
static Object getAttribute(Path path, String attribute, LinkOption... options) Reads the value of a file attribute.
static FileTime getLastModifiedTime(Path path, LinkOption... options) Returns a file’s last modified time.
static UserPrincipal getOwner(Path path, LinkOption... options) Returns the owner of a file.
static Set<PosixFilePermission> getPosixFilePermissions(Path path, LinkOption... options) Returns a file’s POSIX file permissions.
static <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) Returns a file attribute view of a given type.
static FileStore getFileStore(Path path) Returns the FileStore representing the file store where a file is located.

new方法

newBufferedReader

方法 描述
static BufferedReader newBufferedReader(Path path) Opens a file for reading, returning a BufferedReader to read text from the file in an efficient manner.
static BufferedReader newBufferedReader(Path path, Charset cs) Opens a file for reading, returning a BufferedReader that may be used to read text from the file in an efficient manner.

newBufferedWriter

方法 描述
static BufferedWriter newBufferedWriter(Path path, Charset cs, OpenOption... options) Opens or creates a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner.
static BufferedWriter newBufferedWriter(Path path, OpenOption... options) Opens or creates a file for writing, returning a BufferedWriter to write text to the file in an efficient manner.

newByteChannel

方法 描述
static SeekableByteChannel newByteChannel(Path path, OpenOption... options) Opens or creates a file, returning a seekable byte channel to access the file.
static SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) Opens or creates a file, returning a seekable byte channel to access the file.

newDirectoryStream

方法 描述
static DirectoryStream<Path> newDirectoryStream(Path dir) Opens a directory, returning a DirectoryStream to iterate over all entries in the directory.
static DirectoryStream<Path> newDirectoryStream(Path dir, String glob) Opens a directory, returning a DirectoryStream to iterate over the entries in the directory.
static DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter) Opens a directory, returning a DirectoryStream to iterate over the entries in the directory.

newInputStream

方法 描述
static InputStream newInputStream(Path path, OpenOption... options) Opens a file, returning an input stream to read from the file.
static OutputStream newOutputStream(Path path, OpenOption... options) Opens or creates a file, returning an output stream that may be used to write bytes to the file.

write方法

write

方法 描述
static Path write(Path path, byte[] bytes, OpenOption... options) Writes bytes to a file.
static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options) Write lines of text to a file.
static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options) Write lines of text to a file.

writeString

方法 描述
static Path writeString(Path path, CharSequence csq, Charset cs, OpenOption... options) Write a CharSequence to a file.
static Path writeString(Path path, CharSequence csq, OpenOption... options) Write a CharSequence to a file.

walk方法

walk

方法 描述
static Stream<Path> walk(Path start, int maxDepth, FileVisitOption... options) Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.
static Stream<Path> walk(Path start, FileVisitOption... options) Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.

walkFileTree

方法 描述
static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) Walks a file tree.
static Path walkFileTree(Path start, Set<FileVisitOption> options, int maxDepth, FileVisitor<? super Path> visitor) Walks a file tree.

返回流的方法

walk

方法 描述
static Stream<Path> walk(Path start, int maxDepth, FileVisitOption... options) Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.
static Stream<Path> walk(Path start, FileVisitOption... options) Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.

find

方法 描述
static Stream<Path> find(Path start, int maxDepth, BiPredicate<Path,​BasicFileAttributes> matcher, FileVisitOption... options) Return a Stream that is lazily populated with Path by searching for files in a file tree rooted at a given starting file.

lines

方法 描述
static Stream<String> lines(Path path) Read all lines from a file as a Stream.
static Stream<String> lines(Path path, Charset cs) Read all lines from a file as a Stream.

list方法

方法 描述
static Stream<Path> list(Path dir) Return a lazily populated Stream, the elements of which are the entries in the directory.

其他方法

方法 描述
static Path move(Path source, Path target, CopyOption... options) Move or rename a file to a target file.
static String probeContentType(Path path) Probes the content type of a file.
static long size(Path path) Returns the size of a file (in bytes).

程序 Files工具类示例

Files是一个操作文件的工具类,它提供了大量便捷的工具方法,下面程序简单示范了Files类的用法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.nio.file.*;
import java.nio.charset.*;
import java.io.*;
import java.util.*;

public class FilesTest {
public static void main(String[] args) throws Exception {
// 复制文件
Files.copy(Paths.get("FilesTest.java"), new FileOutputStream("a.txt"));
// 判断FilesTest.java文件是否为隐藏文件
System.out.println("FilesTest.java是否为隐藏文件:"
+ Files.isHidden(Paths.get("FilesTest.java")));
// 一次性读取FilesTest.java文件的所有行
List<String> lines = Files.readAllLines(Paths.get("FilesTest.java"), Charset.forName("gbk"));
System.out.println(lines);
// 判断指定文件的大小
System.out.println("FilesTest.java的大小为:" + Files.size(Paths.get("FilesTest.java")));
List<String> poem = new ArrayList<>();
poem.add("水晶潭底银鱼跃");
poem.add("清徐风中碧竿横");
// 直接将多个字符串内容写入指定文件中
Files.write(Paths.get("pome.txt"), poem, Charset.forName("gbk"));
// 使用Java 8新增的Stream API列出当前目录下所有文件和子目录
Files.list(Paths.get(".")).forEach(path -> System.out.println(path));
// 使用Java 8新增的Stream API读取文件内容
Files.lines(Paths.get("FilesTest.java"), Charset.forName("gbk"))
.forEach(line -> System.out.println(line));
FileStore cStore = Files.getFileStore(Paths.get("C:"));
// 判断C盘的总空间,可用空间
System.out.println("C:共有空间:" + cStore.getTotalSpace());
System.out.println("C:可用空间:" + cStore.getUsableSpace());
}
}

上面程序简单示范了Files工具类的用法。

上面示例程序中①号代码使用Stream API列出了指定路径下的所有文件和目录;②号代码则使用了Stream API读取文件内容。