Utils to read resource text file to String (Java)

java 8 read file from resources
java read file from absolute path
java read file from resources
get file path from resource folder java
java write file to resource folder
java resource to string
java inputstream to string
read yaml file from resources java

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.

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

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

Utils to read resource text file to String (Java), Yes, Guava provides this in the Resources class. For example: URL url = Resources.getResource("foo.txt");. String text = Resources.toString(url  Utils to read resource text file to String (Java) Questions: 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. Answers: Yes, Guava provides this in the Resources class.

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.

How to Read a File in Java, Quick code example of the various ways we can read a file with Java. private String readFromInputStream(InputStream inputStream). throws IOException { We'll read the “fileTest.txt” available under src/main/resources: ? Here we pass the File object to the method readFileToString() of FileUtils class. Utils to read resource text file to String (Java) 0 votes 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

For java 7:

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

Load a Resource as a String in Spring, Learn how to inject the contents of a resource file into our beans as a String, with Spring helps us find and read a resource using the resource loader, which We can use Spring's own FileCopyUtils#copyToString method: ? Java “Back to Basics” Tutorial · Jackson JSON Tutorial · HttpClient 4 Tutorial  Many times you want to read contents of a file into String, but, unfortunately, it was not a trivial job in Java, at least not until JDK 1.7. In Java 8, you can read a file into String in just one line of code. Prior to the release of new File IO API, you have to write a lot

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

Utils to read resource text file to String (Java), Utils to read resource text file to String (Java). Posted by: admin November 16, 2017 Leave a comment. Questions: Is there any utility that helps to read a text file​  Two Java examples of reading a file from resources folder in either simple Java application or any spring mvc / spring boot application. Project Structure. Below image describes the folder structure used in this example. Notice the file sample.txt in resources folder.

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

Read file from resources folder - Spring Example, Read file in Spring – ResourceUtils.getFile() getFile( "classpath:config/sample.​txt" ). //File is found String content = new String(Files.readAllBytes(file.toPath()))​;. In this tutorial, we used Apache FileUtils to work with files. You might also be interested in the related tutorials: Creating file in Java, Copying file in Java, Java file size, Reading text files in Java, Reading and writing ICO images in Java, Java Swing tutorial, Java tutorial, Displaying image in Java.

Java Read File to String [Updated for Java 8], readAllBytes, Files.lines and FileReader & BufferedReader to read file content. (to read line by line) and FileReader & BufferedReader to read text file to String. import java.nio.file.Files;. import java.nio.file.Paths;. import java.util.stream. IO – Read file from resources · IO – Read/Write UTF-8 Data · IO – Check if File  I have a text file added as a raw resource. The text file contains text like: b) IF APPLICABLE LAW REQUIRES ANY WARRANTIES WITH RESPECT TO THE SOFTWARE, ALL SUCH WARRANTIES ARE LIMITED IN DURATION TO NINETY (90) DAYS FROM THE DATE OF DELIVERY. (c) NO ORAL OR WRITTEN INFORMATION OR ADVICE GIVEN BY VIRTUAL

Java – Read a file from resources folder – Mkyong.com, How do you read a specific line from a text file in Java? In this tutorial, we'll explore different ways to read from a File in Java. First, we'll see how to load a file from the classpath, a URL or from a JAR file, using standard Java classes. Second, we'll see how to read the content with BufferedReader, Scanner, StreamTokenizer, DataInputStream, SequenceInputStream, and FileChannel .

Read all text from a file into a String in Java, How do I read a resource folder in spring boot? First of all, we saw how to produce a Resource to access the file, and how to read from Resource to String. Next, we also showed how to hide the resource loading implementation, and allow the string contents to be shared across beans by creating qualified beans in an @Configuration , allowing the strings to be autowired.

Comments
  • 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.
  • That's just a text file under classpath like "classpath*:mytext/text.txt"
  • @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/…)
  • @EranMedan: Yes, if you want the context classloader you'd want to use it explicitly.
  • 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.
  • @Arne: What version of Java are you using? There may be something in Java 7 or Java 8...
  • com.google.common.io.Resources is marked unstable according to SonarQube
  • 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'.
  • Is it - or is it not - necessary to close the stream as well? Guava internally closes the stream.
  • 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.
  • change CartApplication.class.getResourceAsStream to CartApplication.class.getClassLoader().getResourceAsStream to load resources in the current jar..like srm/test/resources