我有一个单元测试,需要处理位于src/test/resources/abc.xml
中的XML文件。将文件内容导入String
的最简单方法是什么
发布于 2010-10-11 19:50:17
最后,我找到了一个简洁的解决方案,多亏了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"
);
}
}
效果很好。文件src/test/resources/com/example/abc.xml
已加载(我使用的是Maven)。
比方说,如果用"/foo/test.xml"
替换"abc.xml"
,则将加载此资源:src/test/resources/foo/test.xml
您也可以使用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();
}
}
发布于 2014-11-17 04:59:54
开门见山:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());
发布于 2010-10-08 22:14:14
首先,确保将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 "";
}
}
https://stackoverflow.com/questions/3891375
复制相似问题