NIO详解:Path&Files&FileChannel常用方法
1 Path
JDK7 引入了 Path 和 Paths 类,Path 用来表示文件路径,而Paths 是工具类,用来获取 Path 实例。使用示例如下:
Path source = Paths.get("1.txt"); // 相对路径 使用 user.dir 环境变量来定位 1.txt
Path source = Paths.get("d:\\1.txt"); // 绝对路径 代表了 d:\1.txt
Path source = Paths.get("d:/1.txt"); // 绝对路径 同样代表了 d:\1.txt
Path projects = Paths.get("d:\\data", "projects"); // 代表了 d:\data\projects
另外我们也可以使用以下两种符号表示文件路径
.
代表了当前路径..
代表了上一级路径
例如现有目录结构如下:
d:
|- data
|- projects
|- a
|- b
我们可以编写代码
Path path = Paths.get("d:\\data\\projects\\a\\..\\b");
System.out.println(path);
System.out.println(path.normalize()); // 将path路径正常化,即将路径中的"\."或"\.."变为正常目录名
输出结果
d:\data\projects\a\..\b
d:\data\projects\b
2 Files
1)检查文件是否存在
Path path = Paths.get("helloword/data.txt");
boolean exists = Files.exists(path)
System.out.println(exists);
2)创建一级目录
Path path = Paths.get("helloword/d1");
Files.createDirectory(path);
- 如果目录已存在,会抛异常 FileAlreadyExistsException
- 不能一次创建多级目录,否则会抛异常 NoSuchFileException
3)创建多级目录
Path path = Paths.get("helloword/d1/d2");
Files.createDirectories(path);
4)拷贝文件
Path source = Paths.get("helloword/data.txt");
Path target = Paths.get("helloword/target.txt");
Files.copy(source, target);
如果文件已存在,会抛异常 FileAlreadyExistsException,如果希望用 source 覆盖掉 target,需要用 StandardCopyOption 来控制
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
5)移动文件
Path source = Paths.get("helloword/data.txt");
Path target = Paths.get("helloword/data.txt");
Files.move(