0

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

4

2 回答 2

1

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

}
于 2021-02-23T21:31:58.513 回答
0

我重新创建了您描述的相同场景,并且您的代码对我有用。你能仔细检查一下你的项目看起来像我的下面吗?如果是这样,我怀疑这可能与您的环境有关。

我的项目

于 2021-02-23T21:25:48.743 回答