NIO.2
Path接口
- Path接口是一共用在文件系统中定位文件的对象,通常表示一个依赖于文件系统的文件路径
NIO.2提供了Paths和Files两个工具类,其中Paths类提供了两个返回Path的静态方法,提供静态方法可以创建Path对象,Files类提供大量的静态方法来操作文件
Path中常用方法:
Path getRoot() //返回该路径的根组件作为路径对象,如果此路径没有根组件,返回null
Path getParent() //返回父路径,如果此路径没有父路径,返回null
int getNameCount() //返回路径中名称元素的数量
Path getName(int index) //返回此路径的名称元素作为路径对象
boolean endsWith(String other) //判断当前路径是否以指定的字符串结尾
URI toUri() //返回表示此路径的URI地址
Path toAbsolutePath() //返回表示此路径的绝对路径的路径对象
代码:
package com.Put;
import java.nio.file.Path;
import java.nio.file.Paths;
public class IO {
public static void main(String[] args) throws Exception {
//使用Paths的get()方法创建Path对象
Path path = Paths.get("E:\\Idea\\JavaSE\\重新学习\\src");
//输出path对象中的信息
System.out.println("path的根路径:"+path.getRoot());
System.out.println("path的父路径:"+path.getParent());
System.out.println("path中路径名称数:"+path.getNameCount());
//循环输出路径名称
for (int i = 0; i < path.getNameCount(); i++) {
//获取指定索引处的路径名称
Path name = path.getName(i);
System.out.println("索引为"+i+"的路径名称:"+name);
}
System.out.println("path的URI路径为:"+path.toUri());
System.out.println("path的绝对路径:"+path.toAbsolutePath());
}
}
运行结果:
path的根路径:E:\
path的父路径:E:\Idea\JavaSE\重新学习
path中路径名称数:4
索引为0的路径名称:Idea
索引为1的路径名称:JavaSE
索引为2的路径名称:重新学习
索引为3的路径名称:src
path的URI路径为:file:///E:/Idea/JavaSE/重新学习/src/
path的绝对路径:E:\Idea\JavaSE\重新学习\src
Files工具类
- File工具类是一个操作文件的工具类
Files工具类常用的方法:
static Path createFile(Path path, FileAttribute<?>... attrs) //创建一个新的空文件,如文件存在,则创建失败
static Path createDirectory(Path dir, FileAttribute<?>... attrs) //创建多级目录
static Path write(Path path,Iterable<? extends CharSequence> lines,OpenOption... options)
//将文本行写入文件,并传入指定的写入模式
static List<String> readAllLines(Path path) //从文中读取所有行
static long size(Path path) //返回文件的大小(以字节为单位)
代码如下:
package com.Put;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
public class IO {
public static void main(String[] args) throws Exception {
//定义一个目录路径的Path对象
Path directoryPath = Paths.get("E:\\Idea\\JavaSE\\重新学习\\test");
//根据path创建多级目录
Files.createDirectories(directoryPath);
System.out.println("目录创建成功!");
//定义一个文件路径的Path对象
Path filePath = Paths.get("E:\\Idea\\JavaSE\\重新学习\\test\\test1.txt");
//根据Path对象创建一个文件
Files.createFile(filePath);
//创建一个List集合,向其添加内容
List<String> list = new ArrayList<String>();
list.add("这是一个测试文件");
//将集合中的内容追加写入到指定的文件中
Files.write(filePath,list, StandardOpenOption.APPEND);
List<String> lines = Files.readAllLines(filePath);
System.out.println("文件的大小为:"+Files.size(filePath));
System.out.println("文件的内容为:"+lines);
}
}
运行结果: