Utils to read resource text file to String (Java)

JavaStringTextResources

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

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

Solution 2 - Java

You can use the old [Stupid Scanner trick][1] 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. [1]: https://community.oracle.com/blogs/pat/2004/10/23/stupid-scanner-tricks

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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

Solution 7 - Java

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

Solution 8 - Java

You can use the following code form Java

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

Solution 9 - Java

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

Solution 10 - Java

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.

Solution 11 - Java

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.

Solution 12 - Java

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

Solution 13 - Java

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.

Solution 14 - Java

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

Solution 15 - Java

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

Solution 16 - Java

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

Solution 17 - Java

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

Solution 18 - Java

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.

Solution 19 - Java

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

Solution 20 - Java

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)

Solution 21 - Java

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

Solution 22 - Java

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
}

Solution 23 - Java

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

Solution 24 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLoc PhanView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaakosickiView Answer on Stackoverflow
Solution 3 - JavaKovalsky DmitryiView Answer on Stackoverflow
Solution 4 - JavaLucio PaivaView Answer on Stackoverflow
Solution 5 - JavaLuciano FiandesioView Answer on Stackoverflow
Solution 6 - JavaStefan EndrullisView Answer on Stackoverflow
Solution 7 - JavaAndreas DolkView Answer on Stackoverflow
Solution 8 - JavaRaghu K NairView Answer on Stackoverflow
Solution 9 - JavaGary SheppardView Answer on Stackoverflow
Solution 10 - JavaHarry KaradimasView Answer on Stackoverflow
Solution 11 - JavaWitbrockView Answer on Stackoverflow
Solution 12 - JavaSuraj ChandranView Answer on Stackoverflow
Solution 13 - JavaBullyWiiPlazaView Answer on Stackoverflow
Solution 14 - Javauser1050755View Answer on Stackoverflow
Solution 15 - JavaDillon Ryan ReddingView Answer on Stackoverflow
Solution 16 - JavaMichal KordasView Answer on Stackoverflow
Solution 17 - JavasklimkovitchView Answer on Stackoverflow
Solution 18 - JavaphilipjkimView Answer on Stackoverflow
Solution 19 - JavaJava_Fire_WithinView Answer on Stackoverflow
Solution 20 - JavajolumgView Answer on Stackoverflow
Solution 21 - JavaVikkiView Answer on Stackoverflow
Solution 22 - JavaEspressoView Answer on Stackoverflow
Solution 23 - JavabobmarksieView Answer on Stackoverflow
Solution 24 - JavaKhắc Nghĩa TừView Answer on Stackoverflow