问题描述
我在项目根目录中创建了文件夹 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());
}
}
,
我重新创建了您描述的相同场景,您的代码对我有用。 你能仔细检查一下你的项目在下面看起来像我的吗?如果是这样,我怀疑这可能与您的环境有关。