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


当前回答

一针见血:

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

其他回答

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

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

使用谷歌番石榴:

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)

使用共享。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;
    }
}

好的,对于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目录下。

一针见血:

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