Java中读取资源文本文件到String

发布于 2024-11-08 03:33:14 字数 1539 浏览 9 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

GRAY°灰色天空 2024-11-15 03:33:20

我喜欢 Apache commons 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 ...
    }

I like Apache commons utils for this type of stuff and use this exact use-case (reading files from classpath) extensively when testing, especially for reading JSON files from /src/test/resources as part of unit / integration testing. e.g.

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

}

For testing purposes, it can be nice to catch the IOException and throw a RuntimeException - your test class could look like e.g.

    @Test
    public void shouldDoSomething () {
        String json = FileUtils.getResource("/json/input.json");

        // Use json as part of test ...
    }
_蜘蛛 2024-11-15 03:33:20
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");
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");
ら栖息 2024-11-15 03:33:19

如果您想要逐行返回值作为 List ,Guava 还具有 Files.readLines()

List<String> lines = Files.readLines(new File("/file/path/input.txt"), Charsets.UTF_8);

请参阅 此处 比较 3 种方式(BufferedReader 与 Guava 的 Files 与 Guava 的 Resources)从文本文件中获取String

Guava also has Files.readLines() if you want a return value as List<String> line-by-line:

List<String> lines = Files.readLines(new File("/file/path/input.txt"), Charsets.UTF_8);

Please refer to here to compare 3 ways (BufferedReader vs. Guava's Files vs. Guava's Resources) to get String from a text file.

风向决定发型 2024-11-15 03:33:19

这是我的方法效果很好

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

Here is my approach worked fine

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
    }
}
蘑菇王子 2024-11-15 03:33:19

如果您包含 Guava,那么您可以使用:(

String fileContent = Files.asCharSource(new File(filename), Charset.forName("UTF-8")).read();

其他解决方案提到了 Guava 的其他方法,但它们已被弃用)

If you include Guava, then you can use:

String fileContent = Files.asCharSource(new File(filename), Charset.forName("UTF-8")).read();

(Other solutions mentioned other method for Guava but they are deprecated)

七度光 2024-11-15 03:33:19

以下代码对我有用:

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

The following cods work for me:

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");
沒落の蓅哖 2024-11-15 03:33:19

我制作了这样的无依赖静态方法:

import java.nio.file.Files;
import java.nio.file.Paths;

public class ResourceReader {
    public  static String asString(String resourceFIleName) {
        try  {
            return new String(Files.readAllBytes(Paths.get(new CheatClassLoaderDummyClass().getClass().getClassLoader().getResource(resourceFIleName).toURI())));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
class CheatClassLoaderDummyClass{//cheat class loader - for sql file loading
}

I made NO-dependency static method like this:

import java.nio.file.Files;
import java.nio.file.Paths;

public class ResourceReader {
    public  static String asString(String resourceFIleName) {
        try  {
            return new String(Files.readAllBytes(Paths.get(new CheatClassLoaderDummyClass().getClass().getClassLoader().getResource(resourceFIleName).toURI())));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
class CheatClassLoaderDummyClass{//cheat class loader - for sql file loading
}
ゝ杯具 2024-11-15 03:33:18

我自己也经常遇到这个问题。为了避免对小项目的依赖,我经常
当我不需要 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编辑你的文件,然后将其放入jar中,然后打开的计算机
文件可能将 CP-1251 作为其本机文件编码(例如);所以在
在这种情况下,您永远不知道目标编码,因此显式
编码信息至关重要。
此外,逐个字符读取文件的循环似乎效率低下,但它用于
BufferedReader,所以实际上相当快。

I often had this problem myself. To avoid dependencies on small projects, I often
write a small utility function when I don't need commons io or such. Here is
the code to load the content of the file in a string buffer :

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

Specifying the encoding is important in that case, because you might have
edited your file in UTF-8, and then put it in a jar, and the computer that opens
the file may have CP-1251 as its native file encoding (for example); so in
this case you never know the target encoding, therefore the explicit
encoding information is crucial.
Also the loop to read the file char by char seems inefficient, but it is used on a
BufferedReader, and so actually quite fast.

时光是把杀猪刀 2024-11-15 03:33:18

这是使用 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);
    }
}

Here's a solution using Java 11's 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);
    }
}
一紙繁鸢 2024-11-15 03:33:18

如果您想从文件等项目资源中获取字符串
在项目的 src/main/resources 中的 testcase/foo.json 中,执行以下操作:

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

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

If you want to get your String from a project resource like the file
testcase/foo.json in src/main/resources in your project, do this:

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

Note that the getClassLoader() method is missing on some of the other examples.

平定天下 2024-11-15 03:33:18

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

Use Apache commons's FileUtils. It has a method readFileToString

陌上芳菲 2024-11-15 03:33:18

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

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

不需要第三方依赖项。

I'm using the following for reading resource files from the classpath:

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

No third party dependencies required.

孤君无依 2024-11-15 03:33:18

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

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

At least as of Apache commons-io 2.5, the IOUtils.toString() method supports an URI argument and returns contents of files located inside jars on the classpath:

IOUtils.toString(SomeClass.class.getResource(...).toURI(), ...)
终难遇 2024-11-15 03:33:18

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

With set of static imports, Guava solution can be very compact one-liner:

toString(getResource("foo.txt"), UTF_8);

The following imports are required:

import static com.google.common.io.Resources.getResource
import static com.google.common.io.Resources.toString
import static java.nio.charset.StandardCharsets.UTF_8
望她远 2024-11-15 03:33:18
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;
    }
}
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;
    }
}
谜兔 2024-11-15 03:33:17

yegor256 找到了一个不错的解决方案使用 Apache Commons IO

import org.apache.commons.io.IOUtils;

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

yegor256 has found a nice solution using Apache Commons IO:

import org.apache.commons.io.IOUtils;

String text = IOUtils.toString(this.getClass().getResourceAsStream("foo.xml"),
                               "UTF-8");
谈情不如逗狗 2024-11-15 03:33:17

Guava 有一个“toString”方法,用于将文件读入字符串:

import com.google.common.base.Charsets;
import com.google.common.io.Files;

String content = Files.toString(new File("/home/x1/text.log"), Charsets.UTF_8);

此方法不需要文件位于类路径中(如 Jon Skeet 之前的答案)。

Guava has a "toString" method for reading a file into a String:

import com.google.common.base.Charsets;
import com.google.common.io.Files;

String content = Files.toString(new File("/home/x1/text.log"), Charsets.UTF_8);

This method does not require the file to be in the classpath (as in Jon Skeet previous answer).

茶色山野 2024-11-15 03:33:17

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

apache-commons-io has a utility name FileUtils:

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

String content = FileUtils.readFileToString(myFile, "UTF-8");  // or any other encoding
一梦浮鱼 2024-11-15 03:33:17

我喜欢阿科西基关于愚蠢的扫描仪技巧的回答。这是我看到的最简单的方法,不需要外部依赖,可以在 Java 8 中工作(实际上可以追溯到 Java 5)。这里有一个更简单的答案如果您可以使用 Java 9 或更高版本(因为 InputStream.readAllBytes() 是在 Java 9 中添加的):

String text = new String(
    AppropriateClass.class.getResourceAsStream("foo.txt").readAllBytes(),
    StandardCharsets.UTF_8 // You can probably omit this parameter
);

如果您担心文件名是错误和/或关于关闭流,您可以稍微扩展一下:

String text = null;
InputStream stream = AppropriateClass.class.getResourceAsStream("foo.txt");
if (null != stream) {
    text = stream.readAllBytes();
    stream.close()
}

I like akosicki's answer with the Stupid Scanner Trick. It's the simplest I see without external dependencies that works in Java 8 (and in fact all the way back to Java 5). Here's an even simpler answer if you can use Java 9 or higher (since InputStream.readAllBytes() was added at Java 9):

String text = new String(
    AppropriateClass.class.getResourceAsStream("foo.txt").readAllBytes(),
    StandardCharsets.UTF_8 // You can probably omit this parameter
);

If you're concerned about the filename being wrong and/or about closing the stream, you can expand this a little:

String text = null;
InputStream stream = AppropriateClass.class.getResourceAsStream("foo.txt");
if (null != stream) {
    text = stream.readAllBytes();
    stream.close()
}
肩上的翅膀 2024-11-15 03:33:17

您可以使用以下 Java 代码

new String(Files.readAllBytes(Paths.get(getClass().getResource("example.txt").toURI())));

You can use the following code form Java

new String(Files.readAllBytes(Paths.get(getClass().getResource("example.txt").toURI())));
∝单色的世界 2024-11-15 03:33:16

是的,GuavaGuava 中提供了此功能。 github.io/guava/releases/snapshot/api/docs/com/google/common/io/Resources.html" rel="noreferrer">资源 类。例如:

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

Yes, Guava provides this in the Resources class. For example:

URL url = Resources.getResource("foo.txt");
String text = Resources.toString(url, StandardCharsets.UTF_8);
烟雨凡馨 2024-11-15 03:33:16

您可以使用旧的 愚蠢的扫描仪技巧 oneliner 来完成此操作,而无需任何额外的依赖,如番石榴:

String text = new Scanner(AppropriateClass.class.getResourceAsStream("foo.txt"), "UTF-8").useDelimiter("\\A").next();

伙计们,不要使用第 3 方的东西,除非你真的需要它。 JDK 中已经有很多功能。

You can use the old Stupid Scanner trick oneliner to do that without any additional dependency like guava:

String text = new Scanner(AppropriateClass.class.getResourceAsStream("foo.txt"), "UTF-8").useDelimiter("\\A").next();

Guys, don't use 3rd party stuff unless you really need that. There is a lot of functionality in the JDK already.

青瓷清茶倾城歌 2024-11-15 03:33:16

纯粹、简单、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 来执行其他任务,否则将这些库添加到您的项目中只是为了能够从文件中读取数据似乎有点太多了。

Pure and simple, jar-friendly, Java 8+ solution

This simple method below will do just fine if you're using Java 8 or greater:

/**
 * 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()));
        }
    }
}

And it also works with resources in jar files.

About text encoding: InputStreamReader will use the default system charset in case you don't specify one. You may want to specify it yourself to avoid decoding problems, like this:

new InputStreamReader(isr, StandardCharsets.UTF_8);

Avoid unnecessary dependencies

Always prefer not depending on big, fat libraries. Unless you are already using Guava or Apache Commons IO for other tasks, adding those libraries to your project just to be able to read from a file seems a bit too much.

晚风撩人 2024-11-15 03:33:16

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

For java 7:

new String(Files.readAllBytes(Paths.get(getClass().getResource("foo.txt").toURI())));

For Java 11:

Files.readString(Paths.get(getClass().getClassLoader().getResource("foo.txt").toURI()));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文