是否有一种方法将资源中的文本文件读入字符串?

我想这是一个普遍的需求,但我在谷歌上找不到任何实用工具。


当前回答

我自己也经常遇到这个问题。为了避免对小项目的依赖,我经常 当我不需要commons io之类的时候,写一个小的实用函数。这是 在字符串缓冲区中加载文件内容的代码:

StringBuffer sb = new StringBuffer();

BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("path/to/textfile.txt"), "UTF-8"));
for (int c = br.read(); c != -1; c = br.read()) sb.append((char)c);

System.out.println(sb.toString());   

在这种情况下,指定编码很重要,因为您可能已经指定了 用UTF-8编辑你的文件,然后把它放在一个罐子里,然后打开电脑 该文件可能具有CP-1251作为其原生文件编码(例如);因此,在 在这种情况下,您永远不知道目标编码,因此显式 编码信息是至关重要的。 此外,逐字符读取文件的循环似乎效率很低,但它用于 BufferedReader,非常快。

其他回答

使用Apache commons的FileUtils。它有一个readFileToString方法

我喜欢使用Apache通用utils来处理这类东西,并且在测试时广泛使用这种确切的用例(从类路径读取文件),特别是从/src/test/resources读取JSON文件作为单元/集成测试的一部分。如。

public class FileUtils {

    public static String getResource(String classpathLocation) {
        try {
            String message = IOUtils.toString(FileUtils.class.getResourceAsStream(classpathLocation),
                    Charset.defaultCharset());
            return message;
        }
        catch (IOException e) {
            throw new RuntimeException("Could not read file [ " + classpathLocation + " ] from classpath", e);
        }
    }

}

出于测试目的,捕获IOException并抛出RuntimeException可能会很好——您的测试类可能看起来像例。

    @Test
    public void shouldDoSomething () {
        String json = FileUtils.getResource("/json/input.json");

        // Use json as part of test ...
    }

下面是我的方法

public String getFileContent(String fileName) {
    String filePath = "myFolder/" + fileName+ ".json";
    try(InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath)) {
        return IOUtils.toString(stream, "UTF-8");
    } catch (IOException e) {
        // Please print your Exception
    }
}

通过一组静态导入,Guava解决方案可以非常紧凑的一行程序:

toString(getResource("foo.txt"), UTF_8);

需要导入以下内容:

import static com.google.common.io.Resources.getResource
import static com.google.common.io.Resources.toString
import static java.nio.charset.StandardCharsets.UTF_8

至少在Apache common -io 2.5中,IOUtils.toString()方法支持URI参数,并返回位于类路径上的jar中的文件内容:

IOUtils.toString(SomeClass.class.getResource(...).toURI(), ...)