Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法从STS中的src/test/resources读取资源文件_Java_Spring_Spring Boot_Resources_Sts - Fatal编程技术网

Java 无法从STS中的src/test/resources读取资源文件

Java 无法从STS中的src/test/resources读取资源文件,java,spring,spring-boot,resources,sts,Java,Spring,Spring Boot,Resources,Sts,我在根项目目录中创建了文件夹src/test/resources/,并在文件夹jsons中添加了一个文件作为jsons/server\u request.json 现在,我试图通过调用CommonTestUtilityclass中的静态函数来读取此文件,如下所示: public class CommonTestUtility { public static String getFileAsString(String fileName) throws IOException {

我在根项目目录中创建了文件夹
src/test/resources/
,并在文件夹jsons中添加了一个文件作为
jsons/server\u 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/
但是它仍然无法找到 资源 如何解决这个问题


我重新创建了与您描述的相同的场景,并且您的代码适用于我。 你能再检查一下你的项目是否和我的一样吗?如果是这样,我怀疑这可能与你的环境有关

上面的链接可能会有所帮助。 getResource()方法返回需要更改的URI .getFile()函数,以创建一个。toURI()。 简单代码

私有文件getFileFromResource(字符串文件名)引发URI语法异常{

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

}

是的,这就是我所拥有的,但我使用的是STS 4,也许我跳过了一些步骤,你能解释一下手动创建资源文件夹后所有步骤都做了些什么吗?我可以做得更好,可以告诉你我到底做了什么:看完视频后,如果它仍然不起作用,请告诉我,那样的话,我们可以明天打电话一起解决@GIusepeValiero。是的,我再试了一次,它成功了。我做了同样的事情,只是使用了一个静态方法来获取资源,其他一切都是类似的,仍然面临问题。请使用classLoader.getResourceAsStream(文件名)试试运气。请看文章,它给出了从测试单元资源文件夹读取文件的方法