-
使用Files类来执行那些基本的任务,比如:移动或复制文件,或读取文件内容到一个字符串集合
-
Closer类,提供了一种非常干净的方式,确保Closeable实例被正确的关闭
-
ByteSource 和 CharSource类,提供了不可变的输入流(Input)和读(Reader)
-
ByteSink 和 CharSink类,提供了不可变的输出流(Output)和写(Writer)
-
CharStreams和ByteStreams类,为读Readers、写Writers、输入流InputStreams、输出流OutputStreams 提供了一些静态的实用方法
-
BaseEncoding类,提供了编码和解码字节序列和ASCII字符的方法
文件复制:
File original = new File("D:\\test.txt");
File copy = new File("D:\\test2.txt");
Files.copy(original, copy);
文件移动/重命名:
File original = new File("D:\\test.txt");
File newFile = new File("D:\\test2.txt");
Files.move(original, newFile);
文件读取到String集合:
File file = new File("D:\\test2.txt");
List<String> readLines = Files.readLines(file,Charsets.UTF_8);
Files.readLines还可以接收LineProcessor实例作为额外的附加参数。每一行内容都参数LineProcessor.processLine方法,该方法返回一个布尔值。LineProcessor实例会持续读取文件中的行,直到文件读取完毕或LineProcessor.processLine方法返回false。
假设,我们有包含如下信息的一个文件,是一些书本的信息:
"Savage Tom",Being A Great Cook,Acme Publishers,ISBN- 123456,29.99,1
"Smith Jeff",Art is Fun,Acme Publishers,ISBN-456789,19.99,2
"Vandeley Art",Be an Architect,Acme Publishers,ISBN- 234567,49.99,3
"Jones Fred",History of Football,Acme Publishers,ISBN- 345678,24.99,4
"Timpton Patty",Gardening My Way,Acme Publishers,ISBN- 4567891,34.99,5
我们想要抽取出每行数据中的书本的标题。为了完成这项任务,我们需要对LineProcessor接口做如下的实现:
class ToListLineProcessor implements LineProcessor<List<String>> {
private static final Splitter splitter = Splitter.on(",");
private List<String> bookTitles = Lists.newArrayList();
private static final int TITLE_INDEX = 1;
private int limitLine;
public ToListLineProcessor(int limitLine) {
this.limitLine = limitLine;
}
List<String> readLines = Files.readLines(file, Charsets.UTF_8,new ToListLineProcessor(2));
这里也用到了只读取指定行数。这里是只读取2行。
文件的hash值:
File file = new File("D:\\test2.txt");
HashCode hashCode = Files.hash(file, Hashing.md5());
System.out.println(hashCode);
文件写和追加:
File file = new File("D:\\test2.txt");
file.deleteOnExit();
String hamletQuoteStart = "To be, or not to be";
Files.write(hamletQuoteStart, file, Charsets.UTF_8);
assertThat(Files.toString(file, Charsets.UTF_8), is(hamletQuoteStart));
String hamletQuoteEnd = ",that is the question";
Files.append(hamletQuoteEnd, file, Charsets.UTF_8);//追加
assertThat(Files.toString(file, Charsets.UTF_8), is(hamletQuoteStart + hamletQuoteEnd));
String overwrite = "Overwriting the file";
Files.write(overwrite, file, Charsets.UTF_8);//覆盖写
assertThat(Files.toString(file, Charsets.UTF_8), is(overwrite));
这样做,不需要打开、关闭文件资源。易读,不易出错。