• 使用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. ios--时间格式化(cell业务逻辑处理)

    一.点击更多按钮 1.项目需求      点击更多按钮,从底部弹出一个框  2.怎么从底部弹出一个框?           两种方法:                 一种用 UIActionShee ...

  2. sp_executesql

    execute相信大家都用的用熟了,简写为exec,除了用来执行存储过程,一般都用来执行动态Sql  sp_executesql,sql2005中引入的新的系统存储过程,也是用来处理动态sql的, 如 ...

  3. 【Python】 Subprocess module

    1. subprocess.check_output() 2.subprocess.call() 3. subprocess.check_call() the methods 1.2.3 are ar ...

  4. VM arguments

    VM arguments -Xms256M -Xmx512M -XX:PermSize=256m -XX:MaxPermSize=512m

  5. smarty中增加类似foreach的功能自动加载数据方法

    第一步:在Smarty_Compiler.class.php的_compile_tag函数中增加: 复制代码 代码如下: //加载数据的开始标签case 'load': $this->_push ...

  6. 34、JS/AJAX

      1)回顾JS中核心内容 2)了解WEB1.0和WEB2.0时代的技术与特点 3)理解AJAX的产生背景.工作原理与特点 4)掌握AJAX常用API及应用   声明:服务端使用Servlet技术 一 ...

  7. C#网络爬虫

    CronMaker is a utility which helps you to build cron expressions. CronMaker uses Quartz open source ...

  8. lua 操作中文字符串之截取和长度竖排显示

    前言 在游戏中,我们经常会遇到汉字的多行显示,比如名字竖行显示等.如下图: 为了实现上面的效果,lua实现分行是通过  \n  实现的,所以我们需要取出汉字,然后插入 \n 实现分行效果.还有一种就是 ...

  9. I18N

    App.config <?xml version="1.0" encoding="utf-8" ?> <configuration> & ...

  10. Linq join on 多条件

    var a = from m in DbContext.Set<T1>() join q in DbContext.Set<T2>() on new { m.ID, Phone ...