java - 无法从 STS 中的 src/test/resources 读取资源文件
问题描述
我src/test/resources/
在根项目目录中创建了文件夹,并在其中添加了文件夹jsons中的文件为jsons/server_request.json
.
现在我试图通过调用 CommonTestUtilityclass 中的静态函数来读取这个文件,如下所示:
public class CommonTestUtility {
public static String getFileAsString(String fileName) throws IOException {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
String content = new String(Files.readAllBytes(file.toPath()));
return content;
}
}
现在在调用这个函数时
class ServerTest {
@Test
void test_loadResource() {
String content = CommonTestUtility.getFileAsString("jsons/server_request.json");
}
}
,它给我的错误是:
CommonTestUtility - Cannot invoke "java.net.URL.getFile()" because the return value of "java.lang.ClassLoader.getResource(String)" is null.
我尝试
src/test/resources/
在 Junit ServerTest.java 的运行配置中包含,但仍然无法找到资源如何解决此问题?
解决方案
https://mkyong.com/java/java-read-a-file-from-resources-folder/
上面的链接可能会有所帮助。getResource() 方法返回您需要将 .getFile() 函数更改为的 URI。toURI()。简单的代码
私有文件 getFileFromResource(String fileName) 抛出 URISyntaxException{
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(fileName);
if (resource == null) {
throw new IllegalArgumentException("file not found! " + fileName);
} else {
// failed if files have whitespaces or special characters
//return new File(resource.getFile());
return new File(resource.toURI());
}
}
推荐阅读
- c# - Excel 条件格式 c# 基于数据库中的值
- c# - 当我在基类型中拥有另一个属性的 BsonId 属性时,有没有办法在派生类中使用“Id”属性?
- java - 正则表达式将匹配注释的 SQL 代码
- android - MobilenetV2 在移动设备上实现的问题
- c# - C# 如何在 7z.exe 中完全转义密码?
- excel - 插入带除法的简单公式时出现运行时错误 1004
- javascript - dygraphs.js 和 dygraphs.min.js 之间的行为差异
- c# - 反序列化没有节点名称的 JSON
- docker - 寻找关于 containerd-shim/runc 子进程的解释
- c# - 静态方法不会改变引用类型