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


当前回答

假设文件中的UTF8编码-如果不是,只需省略"UTF8"参数并将使用 每种情况下底层操作系统的默认字符集。

快速的方法在JSE 6 -简单和没有第三方库!

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

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

自Java 9以来的快速方法

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

不过,这两种方法都不适合巨大的文件。

其他回答

你可以使用Junit Rule为你的测试创建一个临时文件夹:

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

一针见血:

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

首先,确保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 "";
    }
}

使用谷歌番石榴:

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)

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

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