[英]How to read a text-file resource into Java unit test?
I have a unit test that needs to work with XML file located in src/test/resources/abc.xml
.我有一个单元测试需要使用位于
src/test/resources/abc.xml
的 XML 文件。 What is the easiest way just to get the content of the file into String
?将文件内容放入
String
的最简单方法是什么?
Finally I found a neat solution, thanks to Apache Commons :最后,感谢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"
);
}
}
Works perfectly.完美运行。 File
src/test/resources/com/example/abc.xml
is loaded (I'm using Maven).文件
src/test/resources/com/example/abc.xml
已加载(我使用的是 Maven)。
If you replace "abc.xml"
with, say, "/foo/test.xml"
, this resource will be loaded: src/test/resources/foo/test.xml
如果将
"abc.xml"
替换为"/foo/test.xml"
,则将加载此资源: src/test/resources/foo/test.xml
You can also use Cactoos :你也可以使用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();
}
}
Right to the point :切中要害:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());
Assume UTF8 encoding in file - if not, just leave out the "UTF8" argument & will use the default charset for the underlying operating system in each case.假设文件中的 UTF8 编码 - 如果不是,只需省略“UTF8”参数 & 将在每种情况下使用底层操作系统的默认字符集。
Quick way in JSE 6 - Simple & no 3rd party library! JSE 6 中的快速方法 - 简单且没有 3rd 方库!
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();
}
}
Quick way in JSE 7 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");
}
Quick way since Java 9自 Java 9 以来的快速方法
new String(getClass().getClassLoader().getResourceAsStream(resourceName).readAllBytes());
Neither intended for enormous files though.不过,它们都不打算用于巨大的文件。
First make sure that abc.xml
is being copied to your output directory.首先确保将
abc.xml
复制到您的输出目录。 Then you should use getResourceAsStream()
:然后你应该使用
getResourceAsStream()
:
InputStream inputStream =
Thread.currentThread().getContextClassLoader().getResourceAsStream("test/resources/abc.xml");
Once you have the InputStream, you just need to convert it into a string.获得 InputStream 后,只需将其转换为字符串。 This resource spells it out: http://www.kodejava.org/examples/266.html .
该资源详细说明: http ://www.kodejava.org/examples/266.html。 However, I'll excerpt the relevent code:
但是,我将摘录相关代码:
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 "";
}
}
With the use of Google Guava:使用谷歌番石榴:
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);
}
}
Example:例子:
String fixture = this.readResource("filename.txt", Charsets.UTF_8)
您可以尝试这样做:
String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");
Here's what i used to get the text files with text.这是我用来获取带有文本的文本文件的内容。 I used commons' IOUtils and guava's Resources.
我使用了 commons 的 IOUtils 和 guava 的 Resources。
public static String getString(String path) throws IOException {
try (InputStream stream = Resources.getResource(path).openStream()) {
return IOUtils.toString(stream);
}
}
You can use a Junit Rule to create this temporary folder for your test:您可以使用 Junit Rule 为您的测试创建这个临时文件夹:
@Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();
File file = temporaryFolder.newFile(".src/test/resources/abc.xml");
OK, for JAVA 8, after a lot of debugging I found that there's a difference between好的,对于JAVA 8,经过大量调试我发现两者之间存在差异
URL tenantPathURI = getClass().getResource("/test_directory/test_file.zip");
and和
URL tenantPathURI = getClass().getResource("test_directory/test_file.zip");
Yes, the /
at the beginning of the path without it I was getting null
!是的,没有它的路径开头的
/
我得到了null
!
and the test_directory
is under the test
directory.并且
test_directory
在test
目录下。
Using Commons.IO, this method works from EITHER a instance method or a static method:使用 Commons.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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.