• 使用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;

}

@Override

public boolean processLine(String line) throws IOException {

if (bookTitles.size() >= limitLine) {

return false;

}

bookTitles.add(Iterables.get(splitter.split(line), TITLE_INDEX));

return true;

}

@Override

public List<String> getResult() {

return bookTitles;

}

}

在这里我们将使用逗号分隔每行,获取这本书的标题,是每行中的第二项,并将标题添加到一个字符串集合中。注意,我们使用了Iterables类,

使用了静态的Iterables.get方法,来获取书本的标题。processLine方法总是返回true,因为我们需要获取所有文件中的书本名。

File file = new File("D:\\test2.txt");

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));

这样做,不需要打开、关闭文件资源。易读,不易出错。

guava学习--File的更多相关文章

  1. Guava学习笔记目录

    Guava 是一个 Google 的基于java1.6的类库集合的扩展项目,包括 collections, caching, primitives support, concurrency libra ...

  2. guava 学习笔记 使用瓜娃(guava)的选择和预判断使代码变得简洁

    guava 学习笔记 使用瓜娃(guava)的选择和预判断使代码变得简洁 1,本文翻译自 http://eclipsesource.com/blogs/2012/06/06/cleaner-code- ...

  3. guava 学习笔记(二) 瓜娃(guava)的API快速熟悉使用

    guava 学习笔记(二) 瓜娃(guava)的API快速熟悉使用 1,大纲 让我们来熟悉瓜娃,并体验下它的一些API,分成如下几个部分: Introduction Guava Collection ...

  4. Guava学习

    Guava学习笔记目录 Guava 是一个 Google 的基于java1.6的类库集合的扩展项目,包括 collections, caching, primitives support, concu ...

  5. [置顶] Guava学习之ArrayListMultimap

    ArrayListMultimap类的继承关系如下图所示: Guava ArrayListMultimap List Multimap 是一个接口,继承自 Multimap 接口.ListMultim ...

  6. [置顶] Guava学习之Splitter

    Splitter:在Guava官方的解释为:Extracts non-overlapping substrings from an input string, typically by recogni ...

  7. [置顶] Guava学习之Iterators

    Iterators类提供了返回Iterator类型的对象或者对Iterator类型对象操作的方法.除了特别的说明,Iterators类中所有的方法都在Iterables类中有相应的基于Iterable ...

  8. [置顶] Guava学习之Lists

    Lists类主要提供了对List类的子类构造以及操作的静态方法.在Lists类中支持构造ArrayList.LinkedList以及newCopyOnWriteArrayList对象的方法.其中提供了 ...

  9. [置顶] Guava学习之Immutable集合

    Immutable中文意思就是不可变.那为什么需要构建一个不可变的对象?原因有以下几点: 在并发程序中,使用Immutable既保证线程安全性,也大大增强了并发时的效率(跟并发锁方式相比).尤其当一个 ...

随机推荐

  1. 网站和Web应用程序的区别

    新建项目里面的(ASP.NET Web 应用程序)主要是做B/S系统的,与winform的开发方式类似.新建网站(ASP.NET 网站)是主要开发网站的.其实你只要跟着教程做就行了.具体区别如下(借鉴 ...

  2. This application is modifying the autolayout engine from a background threa-线程错误

    警告提示:This application is modifying the autolayout engine from a background thread, which can lead to ...

  3. 理解NDCG

    关于NDCG,wiki给点解释很详细,这里我谈谈我的理解. NDCG(Normalized discounted cumulative gain):是用来衡量排序质量的指标. 其中一种计算公式如下: ...

  4. AJAX-----03远古时期的ajax

    用iframe方法实现 <!DOCTYPE html> <html lang="en"> <head> <meta charset=&qu ...

  5. 助手系列之连接mysql数据库

    import MySQLdbdef main(): try: conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='pass',db='a ...

  6. linux服务器性能优化

    1.这里的吞吐率特指Web服务器单位时间内处理的请求.       2.压力测试的前提:1>并发用户数 2>总请求数 3>请求资源描述       3.用户平均请求等待时间主要用户衡 ...

  7. mvn 配置修改

    http://www.cnblogs.com/geektown/p/5705405.html D:\javaInstall\apache-maven-3.3.9-bin\apache-maven-3. ...

  8. android通知栏总结

    通知消息的发送 12-1:消息管理者 NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION ...

  9. Java菜鸟学习 Script 脚本语言(简介)

    script 可以写在head里 也可以写在body里 还可以写在 /html后面 script 也是成对出现的  <script></script> 他有三种常见的对话框 1 ...

  10. php常用函数汇总

    php常用函数汇总   字符串截取:           1.substr('要截取的字符串','从第几个字符开始','到第几个字符结束');             * 截取英文或者数字       ...