---
title: "瓜娃系列 (4) - Resources和Files"
author: "ajoo"
date: "2010-08-16T12:17:52Z"
tags: []
categories: ["编程语言"]
slug: "4-resources-files"
draft: false
lastmod: "2010-08-16T12:35:36Z"
id: 738286
url: "https://ajoo.iteye.com/blog/738286"
---

另外一对我经常需要用到的, 是[Resources](http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/Resources.html)和[Files](http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/Files.html).

一般来说, 如果我有一大块的文本, 或者properties文件, xml, 我会选择把它们存到一个文本文件里, 放到jar里. 然后在运行时, 把这个文件当作资源读出. 这样做比直接存到文件系统里面的好处, 在于它对部署方式不敏感, 不管我的代码如何部署, 我只需要从ClassLoader找到我要的文件就好了.

我可以直接用ClassLoader来寻找我的资源, 象这样:

```

URL url = getClass().getClassLoader().getResource("mypackage/myfile.txt");
if (url == null) {
  throw new IOException("mypackage/myfile.txt 没找到!");
}
...

```

把要找的资源名包括在错误信息中很重要. 很多时候, 或者是部署的问题, 或者是程序错误, getResource()会返回null. 如果你不包括这个资源名, 甚至不做这个null检查就直接用这个url变量, 程序会抛出异常, 但是查找错误相当不方便, 无谓浪费时间.

我也可以用Resources来更方便地做同样的事:

```

URL url = Resources.getResource("mypackage/myfile.txt");

```

[Resources.getResource()](http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/Resources.html#getResource(java.lang.String))自动包括了错误检查.

得到了这个URL, 我就可以从里面读出内容. 如果它是一个文本文件, 我可以用Resources.toString():

```

String content = Resources.toString(url);

```


或者如果我需要按行读出:

```

String[] lines = Resources.readLines(url, Charsets.UTF_8);

```


这里, 要给[com.google.common.base.Charsets](http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Charsets.html)做个广告. 它提供了一些标准的所有平台都支持的Charset常量, 非常非常有用!

而如果是一个二进制文件, 我可以用Resources.toByteArray():

```

byte[] content = Resources.toByteArray(url);

```


相比之下, Files相对不是那么常用. 但是有时候当你需要操作文件的时候, 它提供的工具函数还是很顶事的. 比如, 你可以同样地从文本或二进制文件读取字符串或者字节:

```

String content = Files.toString(textFile, Charsets.UTF_8);
byte[] byteArray = Files.toByteArray(binaryFile);

```

可以向文件里写内容:

```

Files.write(content, textFile, Charsets.ASCII);
Files.write(byteArray, binaryFile);

```

也可以拷贝文件:

```

Files.copy(fromFile, toFile);

```

具体的大家看文档吧, 应该很简单地.