[java] How to read a text-file resource into Java unit test?

I have a unit test that needs to work with XML file located in src/test/resources/abc.xml. What is the easiest way just to get the content of the file into String?

This question is related to java unit-testing

The answer is


Here's what i used to get the text files with text. I used commons' IOUtils and guava's Resources.

public static String getString(String path) throws IOException {
    try (InputStream stream = Resources.getResource(path).openStream()) {
        return IOUtils.toString(stream);
    }
}

You can try doing:

String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");

Assume UTF8 encoding in file - if not, just leave out the "UTF8" argument & will use the default charset for the underlying operating system in each case.

Quick way in JSE 6 - Simple & no 3rd party library!

import java.io.File;
public class FooTest {
  @Test public void readXMLToString() throws Exception {
        java.net.URL url = MyClass.class.getResource("test/resources/abc.xml");
        //Z means: "The end of the input but for the final terminator, if any"
        String xml = new java.util.Scanner(new File(url.toURI()),"UTF8").useDelimiter("\\Z").next();
  }
}

Quick way in JSE 7

public class FooTest {
  @Test public void readXMLToString() throws Exception {
        java.net.URL url = MyClass.class.getResource("test/resources/abc.xml");
        java.nio.file.Path resPath = java.nio.file.Paths.get(url.toURI());
        String xml = new String(java.nio.file.Files.readAllBytes(resPath), "UTF8"); 
  }

Quick way since Java 9

new String(getClass().getClassLoader().getResourceAsStream(resourceName).readAllBytes());

Neither intended for enormous files though.


Right to the point :

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());

With the use of Google Guava:

import com.google.common.base.Charsets;
import com.google.common.io.Resources;

public String readResource(final String fileName, Charset charset) throws Exception {
        try {
            return Resources.toString(Resources.getResource(fileName), charset);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
}

Example:

String fixture = this.readResource("filename.txt", Charsets.UTF_8)

First make sure that abc.xml is being copied to your output directory. Then you should use getResourceAsStream():

InputStream inputStream = 
    Thread.currentThread().getContextClassLoader().getResourceAsStream("test/resources/abc.xml");

Once you have the InputStream, you just need to convert it into a string. This resource spells it out: http://www.kodejava.org/examples/266.html. However, I'll excerpt the relevent code:

public String convertStreamToString(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(
                    new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {        
        return "";
    }
}

You can use a Junit Rule to create this temporary folder for your test:

@Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); File file = temporaryFolder.newFile(".src/test/resources/abc.xml");