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

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


当前回答

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

其他回答

对于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()));

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

import org.apache.commons.io.IOUtils;

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

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

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

下面的代码对我有用:

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");
package test;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            String fileContent = getFileFromResources("resourcesFile.txt");
            System.out.println(fileContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //USE THIS FUNCTION TO READ CONTENT OF A FILE, IT MUST EXIST IN "RESOURCES" FOLDER
    public static String getFileFromResources(String fileName) throws Exception {
        ClassLoader classLoader = Main.class.getClassLoader();
        InputStream stream = classLoader.getResourceAsStream(fileName);
        String text = null;
        try (Scanner scanner = new Scanner(stream, StandardCharsets.UTF_8.name())) {
            text = scanner.useDelimiter("\\A").next();
        }
        return text;
    }
}