Rectangle 27 0

Utils to read resource text file to String (Java)?


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

@Arne: What version of Java are you using? There may be something in Java 7 or Java 8...

@EranMedan: Yes, if you want the context classloader you'd want to use it explicitly.

@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/)

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.

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

Note
Rectangle 27 0

Utils to read resource text file to String (Java)?


String stringFromStream = CharStreams.toString(new InputStreamReader(resourceAsStream, "UTF-8"));
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);

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

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

Note
Rectangle 27 0

Utils to read resource text file to String (Java)?


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

Doesn't work when the resource is in the jar

Explain please why this works, why it is better than other alternatives, and any performance/encoding considerations needed.

It is nio 2 in java 1.7. It's native feture of java. For encoding use new String(bytes, StandardCharsets.UTF_8)

Note
Rectangle 27 0

Utils to read resource text file to String (Java)?


String stringFromStream = CharStreams.toString(new InputStreamReader(resourceAsStream, "UTF-8"));
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);

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

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

Note
Rectangle 27 0

Utils to read resource text file to String (Java)?


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

Best answer of the thread. It works even without the useDelimiter().

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

Is it - or is it not - necessary to close the stream as well? Guava internally closes the stream.

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.

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.

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

Note
Rectangle 27 0

Utils to read resource text file to String (Java)?


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

Doesn't work when the resource is in the jar

Explain please why this works, why it is better than other alternatives, and any performance/encoding considerations needed.

It is nio 2 in java 1.7. It's native feture of java. For encoding use new String(bytes, StandardCharsets.UTF_8)

Note
Rectangle 27 0

Utils to read resource text file to String (Java)?


Doesn't work with resources in jar files though

Note
Rectangle 27 0

Utils to read resource text file to String (Java)?


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

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

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

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

Sorry for downvoting, but I don't like answers that add big dependencies to trivial problems.

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.

Note
Rectangle 27 0

Utils to read resource text file to String (Java)?


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

@Arne: What version of Java are you using? There may be something in Java 7 or Java 8...

@EranMedan: Yes, if you want the context classloader you'd want to use it explicitly.

@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/)

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.

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

Note
Rectangle 27 0

Utils to read resource text file to String (Java)?


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

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 :

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.

Note