'Read a File in Java8 which is not under src folder

I am new to Java and I am trying to read a file from ./resources/filter.txt. I am have written the following function to read the files, so far I am able to read this filter.txt from ./src/test/resources/filter.txt

String loadhere(String filePath) {

    URI resource = this.getClass().getClassLoader().getResource(filePath).toURI();
    Path path = Paths.get(resource);
    String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
    return content;

  }

But this throws Null Pointer exception as .getResouces(filePath) is returning null. After some research I tried to use .getResourceAsStream() But it also throws the same error for me. Any Idea on how to fix this issue?



Solution 1:[1]

You can use the straight foward aproach for your use-case. Pass file name filter.txt to the method.

String loadhere(String fileName) throws IOException {
    Path path = Paths.get("src","test","resources",fileName);
    String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
    return content;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 harry