• Files


    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)*方法来比较两个文件的内容是否完全一致

  • 相关阅读:
    11
    961. N-Repeated Element in Size 2N Array
    用numpy.pad()对图像进行填充及简单的图像处理
    709. To Lower Case
    929. Unique Email Addresses
    771. Jewels and Stones
    谭凯---访谈录
    如何拍照
    主题阅读法
    社会各职业工作重心和流程
  • 原文地址:https://www.cnblogs.com/lijia0511/p/5719781.html
Copyright © 2020-2023  润新知