277

Is there a way to read a text file in the resource into a String?

I suppose this is a popular requirement, but I couldn't find any utility after Googling.

5
  • 1
    please clarify what you mean by "resource text file" vs "text file in resource" - it's not easy to understand what you are trying to achieve.
    – Mat
    May 20, 2011 at 6:27
  • That's just a text file under classpath like "classpath*:mytext/text.txt"
    – Loc Phan
    May 20, 2011 at 6:29
  • 9
    Since java11 there is a specific method for this: Files.readString(Paths.get(getClass().getResource("foo.txt").toURI()), Charset.forName("utf-8"))
    – Roberto
    Feb 20, 2021 at 14:57
  • 1
    @Roberto your method works when I run my program from an exploded folder with classes, but when I package it into jar, Paths.get(...) throws FileSystemNotFoundException
    – morgwai
    Oct 9, 2021 at 4:56
  • IOUtils.resourceToString("/foo/text.txt", StandardCharsets.UTF_8); Jun 20 at 19:39

24 Answers 24

330

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

URL url = Resources.getResource("foo.txt");
String text = Resources.toString(url, StandardCharsets.UTF_8);
13
  • 24
    @JonSkeet This is great, however for web applications it might not be the best solution, the implementation of getResource is using Resource.class.getClassLoader but in web applications, this might not be "your" class loader, so it's recommended (e.g. in [1]) to use Thread.currentThread().getContextClassLoader().getResourceAsStream instead (reference [1]: stackoverflow.com/questions/676250/…)
    – Eran Medan
    Jun 13, 2013 at 20:21
  • 2
    @EranMedan: Yes, if you want the context classloader you'd want to use it explicitly.
    – Jon Skeet
    Jun 13, 2013 at 20:24
  • 7
    In the special case when the resource is next to your class, you can do Resources.toString(MyClass.getResource("foo.txt"), Charsets.UTF_8) which guarantees the use of the correct class loader. Mar 5, 2015 at 17:46
  • 6
    com.google.common.io.Resources is marked unstable according to SonarQube
    – Ghilteras
    Jun 11, 2019 at 1:00
  • 3
    guava has change the implementation. For guava 23 the implementation likes following. ClassLoader loader = MoreObjects.firstNonNull( Thread.currentThread().getContextClassLoader(), Resources.class.getClassLoader());
    – xxy
    Feb 22, 2020 at 12:18
213

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.

6
  • 54
    Avoiding 3rd party is a reasonable principle. Unfortunately the core library seems allergic to modeling real-life use cases. Look at Java 7's Files, and tell me why reading everything from a classpath resource wasn't included there? Or at least using a standardized 'filesystem'. Mar 7, 2014 at 18:36
  • 4
    Is it - or is it not - necessary to close the stream as well? Guava internally closes the stream.
    – virgo47
    Nov 12, 2014 at 13:50
  • Worked beautifully for me too! I agree about the 3rd party thing also: In to many answers, the default response always seems to be to use some third party library - be it from Apache or someone else.
    – Terje Dahl
    Apr 5, 2015 at 8:01
  • 2
    change CartApplication.class.getResourceAsStream to CartApplication.class.getClassLoader().getResourceAsStream to load resources in the current jar..like srm/test/resources Feb 27, 2016 at 6:38
  • 10
    While I've used this, I completely disagree on avoiding 3rd party packages. The fact that in Java, the only way to easily read a file to string is with the scanner trick is pretty sad. The alternative to using a 3rd party lib is that everyone will just create their own wrappers. Guava for IO hands down wins if you have a lot of needs for this kind of operation. Where I WILL agree is that you shouldn't import a 3rd party package if you only have one place in your code where you want to do this. That would be overkill imo. Mar 30, 2016 at 22:21
125

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.

16
  • 7
    @zakmck please try to keep your comments constructive. As you grow up as a mature developer, you learn that sometimes you do want to "reinvent the wheel". For instance, you may need to keep your binary below something threshold size. Libraries often make your application size grow by orders of magnitude. One could argue just the opposite of what you said: "No need to write code. Yeah, let's just import libraries every time". Would you really prefer importing a library just to save you 3 lines of code? I bet that adding the library will increase your LOC by more than that. The key is balance. Dec 8, 2017 at 12:24
  • 6
    Well, not every one is running stuff on the cloud. There are embedded systems everywhere running Java, for example. I just don't see your point in criticizing answers that provide totally valid approaches, given that you mention yourself that you're going to accept the suggestion to use JDK directly in your own code. Anyway, let's please try to keep comments strictly to help improve answers, not to discuss opinions. Dec 8, 2017 at 15:17
  • 1
    Good JDK-only solution. I would only add check if InputStream variable is is null or not.
    – scrutari
    Apr 9, 2018 at 21:02
  • 1
    @RobertBain I edited the answer to add info about the charset warning. Let me know if you find out what went wrong with the class loader in AWS so I can add it to the answer as well. Thanks! Oct 26, 2019 at 18:23
  • 1
    I believe this should be the accepted answer. No deps, modern, simple and readable. Plus it offers alternatives to Java code.
    – wooseop
    Feb 7, 2022 at 9:30
116

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()));
4
  • 4
    Explain please why this works, why it is better than other alternatives, and any performance/encoding considerations needed.
    – nanofarad
    Oct 17, 2014 at 10:12
  • 7
    It is nio 2 in java 1.7. It's native feture of java. For encoding use new String(bytes, StandardCharsets.UTF_8) Oct 17, 2014 at 11:29
  • 12
    in my case I needed getClass().getClassLoader() but otherwise great solution! Dec 2, 2016 at 20:02
  • 29
    This won't work, once the app is package into a jar.
    – Daniel Bo
    Oct 9, 2018 at 14:53
58

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");
4
  • I prefer "" to this in-case this is unavailable
    – user833970
    Jan 15, 2015 at 19:25
  • 14
    Just as compact, but with proper closing of the input stream: IOUtils.toString(this.getClass().getResource("foo.xml"), "UTF-8"). Mar 5, 2015 at 17:52
  • 2
    If this solution doesn't work, try adding getClassLoader() to the method chain: String text = IOUtils.toString( getClass().getClassLoader().getResourceAsStream("foo.xml"), StandardCharsets.UTF_8);
    – Abdull
    Oct 4, 2017 at 10:04
  • 4
    Another example with IOUtils: IOUtils.resourceToString("/foo.xml", StandardCharsets.UTF_8);
    – Alex Rewa
    Aug 18, 2020 at 7:58
55

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).

2
  • 2
    Or if it's an input stream, guava has a nice way for this as well String stringFromStream = CharStreams.toString(new InputStreamReader(resourceAsStream, "UTF-8"));
    – Eran Medan
    Jun 13, 2013 at 20:10
  • 1
    This is deprecated in Guava 24.1
    – Andrey
    Apr 24, 2018 at 18:54
41

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
6
  • 2
    Why do one have to specify the encoding, i don't get that. If I read the file, i just want what is in it, it should figure out what encoding it is like my editor does. When I open in Notepad or ++, I dont tell it what encoding it should use. I am using this method and then afterwards writeStringToFile ... but the contents differ. I get strange tokens in the cloned file.. i don't get why I should have to specify an encoding.
    – mjs
    Dec 20, 2011 at 14:47
  • 13
    @Hamidan, choosing the right encoding is a very complex algorithm. It is often implemented in text editor but they sometimes fail to detect the correct encoding. I would not expect a file reading API to embed such complex algorithm to read my file. Jan 17, 2012 at 11:06
  • 1
    @SecretService Also, those algorithms make use of information like the operating system's language, locale and other regional settings which means that reading a file without specifying an encoding may work on your setup but not on someone else's. Apr 28, 2014 at 8:26
  • 1
    Sorry for downvoting, but I don't like answers that add big dependencies to trivial problems.
    – Arne
    Jul 1, 2016 at 13:54
  • 2
    I don't think this will work if the resource is found inside a jar. Then it won't be a file. May 9, 2018 at 9:08
36

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

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()
}
5
  • 3
    the best answer yet so low rated...
    – morgwai
    Oct 9, 2021 at 6:02
  • @morgwai agreed and it raises the question of how SO considers recency in its weighting of answers to decide how high up the page to put them
    – Lucas Ross
    Sep 15, 2022 at 16:33
  • 1
    getResourceAsStream stream is not closed properly. Also, unfriendly exception on wrong filenames
    – R A
    Feb 23 at 14:16
  • @RA good point. I added a version that includes null-checking and closing the stream. Feb 23 at 14:27
  • @GarySheppard readAllBytes might throw an exception resulting in stream not being closed. I'd suggest you use try-with-resources and leave a single answer.
    – R A
    Feb 23 at 14:36
18

You can use the following code form Java

new String(Files.readAllBytes(Paths.get(getClass().getResource("example.txt").toURI())));
4
  • What import statements are needed to pull in "Files" and "Paths" classes? Jul 1, 2016 at 16:33
  • 2
    both are part of java.nio.file package available from JDK 7+ Jul 14, 2016 at 1:12
  • 7
    Does not work when in a jar file.
    – Displee
    Jun 21, 2020 at 18:47
  • If you want it to work in a jar, replace getClass().getResource("example.txt") with getClass().getClassLoader().getResource("example.txt")
    – Kajzer
    Aug 3, 2021 at 5:35
16

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.

5

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

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.

0
2

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

1
  • 1
    File works only for classpath resources that are, well, files. Not if they are elements in a .jar file, or part of a fat jar, one one of the other classloader implementations.
    – toolforger
    Apr 30, 2020 at 13:37
2

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.

2

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(), ...)
1

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

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.

2
0

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
    }
}
1
  • 3
    Where do IOUtils come from? The source should be referenced clearly.
    – ehecatl
    Apr 16, 2018 at 16:51
0

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)

0

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

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

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 ...
    }
1
  • Charset.defaultCharset() is platform-dependent, encoding should be stated explicitely
    – R A
    Feb 23 at 12:14
-1
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");
1
  • Please add short explanation to your answer. Aug 12, 2016 at 7:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.