我有一个单元测试,需要使用位于src/test/resources/abc.xml中的XML文件。将文件内容放入字符串的最简单方法是什么?
当前回答
你可以试试:
String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");
其他回答
一针见血:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());
你可以试试:
String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");
使用谷歌番石榴:
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);
}
}
多亏了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)。
如果你将“abc.xml”替换为“/foo/test.xml”,这个资源将被加载:src/test/resources/foo/test.xml
你也可以使用仙人掌:
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();
}
}
推荐文章
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- 单元测试反模式目录
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?