Is there any utility that helps 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.
24 Answers
Yes, Guava provides this in the Resources
class. For example:
URL url = Resources.getResource("foo.txt");
String text = Resources.toString(url, StandardCharsets.UTF_8);
-
23@JonSkeet This is great, however for web applications it might not be the best solution, the implementation of
getResource
is usingResource.class.getClassLoader
but in web applications, this might not be "your" class loader, so it's recommended (e.g. in [1]) to useThread.currentThread().getContextClassLoader().getResourceAsStream
instead (reference [1]: stackoverflow.com/questions/676250/…) Jun 13, 2013 at 20:21 -
2@EranMedan: Yes, if you want the context classloader you'd want to use it explicitly. Jun 13, 2013 at 20:24
-
7In 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 -
4
com.google.common.io.Resources
is marked unstable according to SonarQube 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());
– xxyFeb 22, 2020 at 12:18
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.
-
52Avoiding 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
-
3Is it - or is it not - necessary to close the stream as well? Guava internally closes the stream.– virgo47Nov 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. Apr 5, 2015 at 8:01
-
2change
CartApplication.class.getResourceAsStream
toCartApplication.class.getClassLoader().getResourceAsStream
to load resources in the current jar..like srm/test/resources Feb 27, 2016 at 6:38 -
9While 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
For java 7:
new String(Files.readAllBytes(Paths.get(getClass().getResource("foo.txt").toURI())));
For Java 11:
Files.readString(Paths.get(getClass().getResource("foo.txt").toURI()));
-
4Explain please why this works, why it is better than other alternatives, and any performance/encoding considerations needed. Oct 17, 2014 at 10:12
-
7It 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
-
11in my case I needed
getClass().getClassLoader()
but otherwise great solution! Dec 2, 2016 at 20:02 -
21
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.
"Simple" method? You must be kidding me
I understand that pure Java does not do a good job when it comes to doing simple tasks like this. For instance, this is how we read from a file in Node.js:
const fs = require("fs");
const contents = fs.readFileSync("some-file.txt", "utf-8");
Simple and easy to read (although people still like to rely on many dependencies anyway, mostly due to ignorance). Or in Python:
with open('some-file.txt', 'r') as f:
content = f.read()
It's sad, but it's still simple for Java's standards and all you have to do is copy the method above to your project and use it. I don't even ask you to understand what is going on in there, because it really doesn't matter to anyone. It just works, period :-)
-
5@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
-
3Well, 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
-
1Good JDK-only solution. I would only add check if
InputStream
variableis
isnull
or not.– scrutariApr 9, 2018 at 21:02 -
2
-
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
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).
-
2Or if it's an input stream, guava has a nice way for this as well
String stringFromStream = CharStreams.toString(new InputStreamReader(resourceAsStream, "UTF-8"));
Jun 13, 2013 at 20:10 -
1
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");
-
-
13Just 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 -
2If this solution doesn't work, try adding
getClassLoader()
to the method chain:String text = IOUtils.toString( getClass().getClassLoader().getResourceAsStream("foo.xml"), StandardCharsets.UTF_8);
– AbdullOct 4, 2017 at 10:04 -
2Another example with IOUtils:
IOUtils.resourceToString("/foo.xml", StandardCharsets.UTF_8);
Aug 18, 2020 at 7:58
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
-
1Why 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.– mjsDec 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
-
-
2I 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
You can use the following code form Java
new String(Files.readAllBytes(Paths.get(getClass().getResource("example.txt").toURI())));
-
What import statements are needed to pull in "Files" and "Paths" classes? Jul 1, 2016 at 16:33
-
2
-
4
-
If you want it to work in a jar, replace
getClass().getResource("example.txt")
withgetClass().getClassLoader().getResource("example.txt")
– KajzerAug 3, 2021 at 5:35
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());
-
3
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.
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.
Use Apache commons's FileUtils. It has a method readFileToString
-
1File 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. Apr 30, 2020 at 13:37
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.
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(), ...)
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);
}
}
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
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;
}
}
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.
-
-
@e-info128
Charsets
is also in Guava. See this: google.github.io/guava/releases/23.0/api/docs Sep 18, 2017 at 2:14
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
}
}
-
3Where do IOUtils come from? The source should be referenced clearly.– ehecatlApr 16, 2018 at 16:51
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)
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");
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
}
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 ...
}
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");
Files.readString(Paths.get(getClass().getResource("foo.txt").toURI()), Charset.forName("utf-8"))
Paths.get(...)
throwsFileSystemNotFoundException