首页 > 解决方案 > 无法从 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 的运行配置中包含,但仍然无法找到资源如何解决此问题?

标签: javaspringspring-bootresourcessts

解决方案


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());
    }

}

推荐阅读