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

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


当前回答

如果您想从项目资源(如文件)中获取String testcase / foo。Json在src/main/resources在你的项目,这样做:

String myString= 
 new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("testcase/foo.json").toURI())));

请注意,在其他一些示例中缺少getClassLoader()方法。

其他回答

下面是一个使用Java 11的Files.readString的解决方案:

public class Utils {
    public static String readResource(String name) throws URISyntaxException, IOException {
        var uri = Utils.class.getResource("/" + name).toURI();
        var path = Paths.get(uri);
        return Files.readString(path);
    }
}

我自己也经常遇到这个问题。为了避免对小项目的依赖,我经常 当我不需要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,非常快。

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

下面的代码对我有用:

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

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

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