Guava Files 简单API使用

关键工具类

import com.google.common.io.Files;
类似的,在Java8中也有一个Files工具类: java.nio.file.Files
注意两者的区别。

1、将字节内容写入到文件File,可以指定编码
com.google.common.io.Files#write(byte[], java.io.File)

final File newFile = new File("E:/b.txt");
Files.write("this is a test".getBytes(), newFile);
/* 再次写入会把之前的内容冲掉*/
Files.write("我是好人".getBytes(), newFile);
/*追加写*/
Files.append("他是坏人", newFile, Charset.defaultCharset());

2、按行一次将文件内容读入到内存中
- com.google.common.io.Files#readLines(java.io.File, java.nio.charset.Charset)
- com.google.common.io.Files#readLines(java.io.File, java.nio.charset.Charset, com.google.common.io.LineProcessor)

- 读首行 com.google.common.io.Files#readFirstLine

// 简单读
final File newFile = new File("E:/b.txt");
List<String> lines = Files.readLines(newFile, Charset.defaultCharset());
lines.forEach(System.out::println);

// 带有文本行处理器的“读”
final File newFile = new File("E:/b.txt");
 /* LineProcessor --> 数据行处理器 */
 Integer lines = Files.readLines(newFile, Charset.defaultCharset(), new LineProcessor<Integer>() {
     private int lineNum = 0;

     /*This method will be called once for each line.*/
     @Override
     public boolean processLine(String line) throws IOException {
         lineNum++;
         return true;
     }

     /*Return the result of processing all the lines. NOT the result of EACH line */
     @Override
     public Integer getResult() {
         return lineNum;
     }
 });
 System.out.println(lines);

3、一次将文件中内容全部读出来 com.google.common.io.Files#toString

final File newFile = new File("E:/b.txt");
String allContent = Files.toString(newFile, Charset.defaultCharset());
System.out.println(allContent);

4、把文件读成字节 com.google.common.io.Files#readBytes
5、从一个文件拷贝到另一个文件 Files.copy(File from, File to)
6、移动文件 Files.move()
7、更新文件时间戳Files.touch()
8、比较两个文件之间的内容是不是完全一致的 Files.equals(File file1,File file2)
9、touch方法创建或者更新文件的时间戳。
10、createTempDir()方法创建临时目录
11、Files.createParentDirs(File) 创建父级目录(只是递归创建父级记录,不会把这个文件也移动)
12、getChecksum(File)获得文件的checksum
13、hash(File)获得文件的hash
14、map系列方法获得文件的内存映射
15、getFileExtension(String)获得文件的扩展名
16、getNameWithoutExtension(String file)获得不带扩展名的文件名

猜你喜欢

转载自blog.csdn.net/qq_30118563/article/details/80334866