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

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


当前回答

public static byte[] readResoureStream(String resourcePath) throws IOException {
    ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
    InputStream in = CreateBffFile.class.getResourceAsStream(resourcePath);

    //Create buffer
    byte[] buffer = new byte[4096];
    for (;;) {
        int nread = in.read(buffer);
        if (nread <= 0) {
            break;
        }
        byteArray.write(buffer, 0, nread);
    }
    return byteArray.toByteArray();
}

Charset charset = StandardCharsets.UTF_8;
String content = new   String(FileReader.readResoureStream("/resource/...*.txt"), charset);
String lines[] = content.split("\\n");

其他回答

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

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

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

import org.apache.commons.io.IOUtils;

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

apache-commons-io有一个实用程序名为FileUtils:

URL url = Resources.getResource("myFile.txt");
File myFile = new File(url.toURI());

String content = FileUtils.readFileToString(myFile, "UTF-8");  // or any other encoding

下面是我的方法

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

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