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

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


当前回答

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

其他回答

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

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

import org.apache.commons.io.IOUtils;

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

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

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() : "";
        }
    }
}

不需要第三方依赖。

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

纯粹而简单,jar友好的Java 8+解决方案

如果你使用的是Java 8或更高版本,下面这个简单的方法就可以了:

/**
 * Reads given resource file as a string.
 *
 * @param fileName path to the resource file
 * @return the file's contents
 * @throws IOException if read fails for any reason
 */
static String getResourceFileAsString(String fileName) throws IOException {
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    try (InputStream is = classLoader.getResourceAsStream(fileName)) {
        if (is == null) return null;
        try (InputStreamReader isr = new InputStreamReader(is);
             BufferedReader reader = new BufferedReader(isr)) {
            return reader.lines().collect(Collectors.joining(System.lineSeparator()));
        }
    }
}

它还可以处理jar文件中的资源。

关于文本编码:如果您没有指定,InputStreamReader将使用默认的系统字符集。你可能想要自己指定它来避免解码问题,像这样:

new InputStreamReader(isr, StandardCharsets.UTF_8);

避免不必要的依赖

总是不喜欢依赖于大而胖的库。除非您已经将Guava或Apache Commons IO用于其他任务,否则将这些库添加到项目中只是为了能够从文件中读取,这似乎有点过分。