简体   繁体   中英

Not able to read resource files from src/test/resources in STS

I created folder src/test/resources/ in root project directory, and inside this I added a file in folder jsons as jsons/server_request.json .

Now I am trying to read this file by calling a the static function in CommonTestUtilityclass given as:

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

Now while calling this function as

class ServerTest {
@Test
void test_loadResource() {
    String content = CommonTestUtility.getFileAsString("jsons/server_request.json");
}

}

, It's giving me the error as:

CommonTestUtility - Cannot invoke "java.net.URL.getFile()" because the return value of "java.lang.ClassLoader.getResource(String)" is null.

I tried to include the src/test/resources/ in the run configuration of Junit ServerTest.java, but still it's not able to find out the resource How to resolve this issue?

https://mkyong.com/java/java-read-a-file-from-resources-folder/

This above link might be helpful. The getResource() method return an URI you need to change.getFile() function to. toURI(). Simple code

private File getFileFromResource(String fileName) throws 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());
    }

}

I recreated the same scenario you describe and your code works for me. Could you double-check that your project looks like mine below? If so, I suspect it might be something with your environment.

我的项目

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM