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());
# 1 楼答案
切中要害:
# 2 楼答案
首先确保
abc.xml
正在复制到输出目录。然后您应该使用getResourceAsStream()
:一旦你有了InputStream,你只需要把它转换成一个字符串。此资源将其详细说明:http://www.kodejava.org/examples/266.html。但是,我将摘录相关代码:
# 3 楼答案
使用谷歌番石榴:
例如:
# 4 楼答案
您可以尝试执行以下操作:
# 5 楼答案
假设文件中使用UTF8编码-如果不是,只需省略“UTF8”参数&;将使用 在每种情况下,基础操作系统的默认字符集
JSE 6中的快速方法-简单和;没有第三方图书馆强>
JSE 7中的快捷方式
自Java 9以来的快捷方式
不过,这两种方法都不适用于大型文件
# 6 楼答案
最后,由于Apache Commons,我找到了一个简洁的解决方案:
工作完美。文件
src/test/resources/com/example/abc.xml
已加载(我正在使用Maven)如果将
"abc.xml"
替换为"/foo/test.xml"
,则将加载此资源:src/test/resources/foo/test.xml
您还可以使用Cactoos: