如何解决无法从 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() 方法返回您需要更改的 URI .getFile() 函数。 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());
}
}
,
我重新创建了您描述的相同场景,您的代码对我有用。 你能仔细检查一下你的项目在下面看起来像我的吗?如果是这样,我怀疑这可能与您的环境有关。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。