Files

write
  public static void write(CharSequence from, File to, Charset charset) throws IOException {
asCharSink(to, charset, new FileWriteMode[0]).write(from);
}
write
  public static void write(byte[] from, File to) throws IOException {
asByteSink(to, new FileWriteMode[0]).write(from);
}

Files类提供了几种方法来通过ByteSink和CharSink类操作文件。

readLines
 public static List<String> readLines(File file, Charset charset) throws IOException {
return (List)readLines(file, charset, new LineProcessor() {
final List<String> result = Lists.newArrayList(); public boolean processLine(String line) {
this.result.add(line);
return true;
} public List<String> getResult() {
return this.result;
}
});
} public static <T> T readLines(File file, Charset charset, LineProcessor<T> callback) throws IOException {
return asCharSource(file, charset).readLines(callback);
}

这个readLines的重载,需要我们实现一个LineProcessor的泛型接口,在这个接口的实现方法processLine方法中我们可以对行文本进行处理,getResult方法可以获得一个最终的处理结果,一般是大文件的读取会用到这个。

另外还有readBytes方法可以对文件的字节做处理,readFirstLine可以返回第一行的文本,Files.toString(File,Charset)可以返回文件的所有文本内容。

equal
  public static boolean equal(File file1, File file2) throws IOException {
Preconditions.checkNotNull(file1);
Preconditions.checkNotNull(file2);
if(file1 != file2 && !file1.equals(file2)) {
long len1 = file1.length();
long len2 = file2.length();
return len1 != 0L && len2 != 0L && len1 != len2?false:asByteSource(file1).contentEquals(asByteSource(file2));
} else {
return true;
}
}

Guava中提供了{*}Files.equal(File,File)*方法来比较两个文件的内容是否完全一致

上一篇:Spring邮件发送2


下一篇:jquery自定义插件——以 选项卡插件为例