Java7中文件IO发生了很大的变化,专门引入了很多新的类:
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
……等等,来取代原来的基于java.io.File的文件IO操作方式.
- Path就是取代File的
A Path represents a path that is hierarchical and composed of a sequence of directory and file name elements separated by a special separator or delimiter.
Path用于来表示文件路径和文件。可以有多种方法来构造一个Path对象来表示一个文件路径,或者一个文件:
1)首先是final类Paths的两个static方法,如何从一个路径字符串来构造Path对象:
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 path3 = FileSystems.getDefault().getPath(“C:/”, “access.log”);
3)File和Path之间的转换,File和URI之间的转换:
File file = new File("C:/my.ini");
Path p1 = file.toPath();
p1.toFile();
file.toURI();
4)创建一个文件:
复制代码
Path target2 = Paths.get(“C:\mystuff.txt”);
// Set perms = PosixFilePermissions.fromString(“rw-rw-rw-“);
// FileAttribute