我有一个单元测试,需要使用位于src/test/resources/abc.xml中的XML文件。将文件内容放入字符串的最简单方法是什么?


当前回答

使用谷歌番石榴:

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

例子:

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

其他回答

首先,确保abc.xml被复制到输出目录。然后你应该使用getResourceAsStream():

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

获得InputStream后,只需将其转换为字符串。这个资源详细说明:http://www.kodejava.org/examples/266.html。但是,我将摘录相关代码:

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

你可以试试:

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

这是我用来获得文本文件与文本。我使用了commons的IOUtils和guava的Resources。

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

好的,对于JAVA 8,经过大量的调试 我发现两者之间是有区别的

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

and

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

是的,在路径开始的/没有它,我得到null!

test_directory在test目录下。

使用共享。IO,这个方法工作在实例方法或静态方法:

public static String loadTestFile(String fileName) {
    File file = FileUtils.getFile("src", "test", "resources", fileName);
    try {
        return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
    } catch (IOException e) {
        log.error("Error loading test file: " + fileName, e);
        return StringUtils.EMPTY;
    }
}