检查文件和文件夹
要检查文件是否存在,我们使用 exists API:
Path path = Paths.get("D:/temp/test/test1");System.out.println(Files.exists(path));
我们还可以检查一个文件是像 myfile.txt 这样的普通文件还是只是一个目录,我们使用 isRegularFile API:
Path path = Paths.get("D:/temp/");System.out.println(Files.isRegularFile(path));
创建文件和文件夹
创建文件夹
try {Path path = Paths.get("D:/temp/test");Files.createDirectory(path);} catch (IOException e) {e.printStackTrace();}
创建多级文件夹
try {Path path = Paths.get("D:/temp/test/test1");Files.createDirectories(path);} catch (IOException e) {e.printStackTrace();}
创建文件
为了防止文件夹不存在,先要创建文件夹,再创建文件。
try {Path path = Paths.get("D:/temp/test1/test.txt");Path parent = path.getParent();if (!Files.exists(parent)) {Files.createDirectories(parent);}Files.createFile(path);} catch (IOException e) {e.printStackTrace();}
创建临时文件
在本地文件系统生成一个文件,不需要指定文件名称。
try {String prefix = "log_";String suffix = ".txt";Path p = Paths.get("D:/temp");Files.createTempFile(p, prefix, suffix);} catch (IOException e) {e.printStackTrace();}
p 给定创建临时文件路径;
prefix,suffix 可以为空字符串,分别指定文件名前缀、后缀。
读写文件
读取文本
// 一次按行读取文件所有内容List<String> lines = Files.readAllLines(path);
写入文本
/* 一次写所有文件内容 */// 写一个字符串到文件Files.write(path, content.getBytes(charset));// 追加字符串到文件Files.write(path, content.getBytes(charset), StandardOpenOption.APPEND);// 写一个行的集合到文件List<String> lines = new ArrayList<String>();Files.write(path, lines);
处理大文件
要处理大文件和二进制文件,需要用到输入流/输出流,或者使用读入器/写入器。
InputStream in = Files.newInputStream(path);OutputStream out = Files.newOutputStream();Reader reader = Files.newBufferedReader(path, charset);Writer writer = Writer.newBufferedWriter(path, charset);
访问目录各项
遍历指定目录下各项
Files.list 会返回Stream,而且是惰性读取,处理目录具有大量项时高效。不过,list 不会进入子目录,进入子目录使用 walk。
// 读取目录涉及需要关闭系统资源, 使用try块. 不进入子目录try(Stream<Path> entries = Files.list(dirPath)) {// 打印每个entries项, 也就是打印每个pathentries.forEach(System.out::println);}// 会进入子目录try(Stream<Path> entries = Files.walk(dirPath)) {entries.forEach(System.out.println);}
