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

JavaUnit Testing

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

Finally I found a neat solution, thanks to Apache Commons:

package com.example;
import org.apache.commons.io.IOUtils;
public class FooTest {
  @Test 
  public void shouldWork() throws Exception {
    String xml = IOUtils.toString(
      this.getClass().getResourceAsStream("abc.xml"),
      "UTF-8"
    );
  }
}

Works perfectly. File src/test/resources/com/example/abc.xml is loaded (I'm using Maven).

If you replace "abc.xml" with, say, "/foo/test.xml", this resource will be loaded: src/test/resources/foo/test.xml

You can also use Cactoos:

package com.example;
import org.cactoos.io.ResourceOf;
import org.cactoos.io.TextOf;
public class FooTest {
  @Test 
  public void shouldWork() throws Exception {
    String xml = new TextOf(
      new ResourceOf("/com/example/abc.xml") // absolute path always!
    ).asString();
  }
}

Solution 2 - Java

Right to the point :

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

Solution 3 - Java

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.

Solution 4 - Java

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

Solution 5 - Java

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)

Solution 6 - Java

You can try doing:

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

Solution 7 - Java

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

Solution 8 - Java

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

Solution 9 - Java

OK, for JAVA 8, after a lot of debugging I found that there's a difference between

URL tenantPathURI = getClass().getResource("/test_directory/test_file.zip");

and

URL tenantPathURI = getClass().getResource("test_directory/test_file.zip");

Yes, the / at the beginning of the path without it I was getting null!

and the test_directory is under the test directory.

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
Questionyegor256View Question on Stackoverflow
Solution 1 - Javayegor256View Answer on Stackoverflow
Solution 2 - Javapablo.vixView Answer on Stackoverflow
Solution 3 - JavaGlen BestView Answer on Stackoverflow
Solution 4 - JavaKirk WollView Answer on Stackoverflow
Solution 5 - JavaDatageekView Answer on Stackoverflow
Solution 6 - JavaGuido CeladaView Answer on Stackoverflow
Solution 7 - JavaikryvorotenkoView Answer on Stackoverflow
Solution 8 - JavaIgorGanapolskyView Answer on Stackoverflow
Solution 9 - JavaKhogaEslamView Answer on Stackoverflow