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

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


当前回答

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

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

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

其他回答

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

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

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

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

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

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

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

我使用以下从类路径读取资源文件:

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Scanner;

public class ResourceUtilities
{
    public static String resourceToString(String filePath) throws IOException, URISyntaxException
    {
        try (InputStream inputStream = ResourceUtilities.class.getClassLoader().getResourceAsStream(filePath))
        {
            return inputStreamToString(inputStream);
        }
    }

    private static String inputStreamToString(InputStream inputStream)
    {
        try (Scanner scanner = new Scanner(inputStream).useDelimiter("\\A"))
        {
            return scanner.hasNext() ? scanner.next() : "";
        }
    }
}

不需要第三方依赖。