0

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?

tusharRawat
  • 719
  • 10
  • 24

2 Answers2

2

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

}
Amit Kumar
  • 99
  • 1
  • 1
  • 7
  • I did same thing just used a static method to get a resource else everything is similar, still facing issue. – tusharRawat Feb 23 '21 at 22:37
  • try your luck with classLoader.getResourceAsStream(fileName).Please look on the article it has given the method to read the file from Test unit resource folder – Amit Kumar Feb 24 '21 at 03:13
0

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.

My Project

Andy Valerio
  • 851
  • 6
  • 13