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

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


当前回答

yegor256用Apache Commons IO找到了一个很好的解决方案:

import org.apache.commons.io.IOUtils;

String text = IOUtils.toString(this.getClass().getResourceAsStream("foo.xml"),
                               "UTF-8");

其他回答

通过一组静态导入,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

是的,Guava在Resources类中提供了这一点。例如:

URL url = Resources.getResource("foo.txt");
String text = Resources.toString(url, StandardCharsets.UTF_8);

yegor256用Apache Commons IO找到了一个很好的解决方案:

import org.apache.commons.io.IOUtils;

String text = IOUtils.toString(this.getClass().getResourceAsStream("foo.xml"),
                               "UTF-8");

我喜欢使用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 ...
    }

Guava有一个“toString”方法用于将文件读入String:

import com.google.common.base.Charsets;
import com.google.common.io.Files;

String content = Files.toString(new File("/home/x1/text.log"), Charsets.UTF_8);

这个方法不需要文件在类路径中(就像Jon Skeet之前的回答一样)。