码迷,mamicode.com
首页 > 其他好文 > 详细

Files

时间:2016-07-29 22:52:09      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

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

 

write
1  public static void write(byte[] from, File to) throws IOException {
2         asByteSink(to, new FileWriteMode[0]).write(from);
3     }

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

readLines
 1 public static List<String> readLines(File file, Charset charset) throws IOException {
 2         return (List)readLines(file, charset, new LineProcessor() {
 3             final List<String> result = Lists.newArrayList();
 4 
 5             public boolean processLine(String line) {
 6                 this.result.add(line);
 7                 return true;
 8             }
 9 
10             public List<String> getResult() {
11                 return this.result;
12             }
13         });
14     }
15 
16     public static <T> T readLines(File file, Charset charset, LineProcessor<T> callback) throws IOException {
17         return asCharSource(file, charset).readLines(callback);
18     }

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

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

equal
 1  public static boolean equal(File file1, File file2) throws IOException {
 2         Preconditions.checkNotNull(file1);
 3         Preconditions.checkNotNull(file2);
 4         if(file1 != file2 && !file1.equals(file2)) {
 5             long len1 = file1.length();
 6             long len2 = file2.length();
 7             return len1 != 0L && len2 != 0L && len1 != len2?false:asByteSource(file1).contentEquals(asByteSource(file2));
 8         } else {
 9             return true;
10         }
11     }

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

Files

标签:

原文地址:http://www.cnblogs.com/lijia0511/p/5719781.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!