Files和Path

在Java1.7之前,Java提供了java.io.File来对文件进行操作,但是它却并不那么完美:

  • 不会在平台中以一贯的方式来处理文件名

  • 不支持高效文件属性访问

  • 不允许复杂应用程序利用可用的文件系统特定特性(比如,符号链接)

  • 大多数方法在出错时仅返回失败,而不会提供异常信息。

从Java 1.7开始,NIO2中提供了新的操作文件的方式:通过Files和Path。

Path

Path用于来表示文件路径或者文件:APathrepresents a path that is hierarchical and composed of a sequence of directory and file name elements separated by a special separator or delimiter。

构造Path对象

(1)使用Paths工具类的两个static方法

Path path = Paths.get("C:/", "Xmp");
Path path2 = Paths.get("C:/Xmp");

URI u = URI.create("file:///C:/Xmp/dd");        
Path p = Paths.get(u);

(2)使用FileSystems

Path path = FileSystems.getDefault().getPath("C:/", "access.log");

File和Path之间的转换

Files

创建文件/目录:Files.createFile(path)/Files.createDirectories(path)

读取文件:Files.newBufferedReader

这里如果指定的字符编码不对,可能会抛出异常MalformedInputException,或者读取到乱码。

写入:Files.newBufferedWriter

复制

获取/设置文件属性

遍历一个文件夹:Files.newDirectoryStream(dir)/Files.list(path)

递归遍历一个目录:Files.walkFileTree

参考

文件系统 API

Java7新特性之文件操作

Last updated