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

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


当前回答

对于java 7:

new String(Files.readAllBytes(Paths.get(getClass().getResource("foo.txt").toURI())));

对于Java 11:

Files.readString(Paths.get(getClass().getClassLoader().getResource("foo.txt").toURI()));

其他回答

下面的代码对我有用:

compile group: 'commons-io', name: 'commons-io', version: '2.6'

@Value("classpath:mockResponse.json")
private Resource mockResponse;

String mockContent = FileUtils.readFileToString(mockResponse.getFile(), "UTF-8");

下面是我的方法

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
    }
}

我喜欢akosicki用愚蠢的扫描仪技巧回答的问题。这是我在Java 8中看到的最简单的没有外部依赖的工作(实际上一直追溯到Java 5)。如果你可以使用Java 9或更高版本(因为InputStream.readAllBytes()是在Java 9中添加的),这里有一个更简单的答案:

String text = new String(AppropriateClass.class.getResourceAsStream("foo.txt")
    .readAllBytes());

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

URL url = Resources.getResource("foo.txt");
String text = Resources.toString(url, StandardCharsets.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