'Read entire File to String Spring Boot [duplicate]

I have a text file with path as resources/templates/temp.txt. I tried reading it with built in Files.readAllBytes() function found in java.nio but that results in an NullPointerException. My code looks as follows:

try {
        File file = new File(getClass().getResource("templates/temp.txt").getFile());
        String temp = new String(Files.readAllBytes(Paths.get(file.getPath())));
        System.out.println(temp);
    }catch(Exception e){
        e.printStackTrace();
    }

The file actually does exist at this location because I am able to get an InputStream and use that in an InputStreamReader and BufferedReader to read the file line-by-line.

    InputStream input = this.getClass().getClassLoader().getResourceAsStream(path)
    //path here is "templates/temp.txt"

I would like to read this file with a built in method rather than iterating over the entire thing. Would appreciate it very much if someone can help with this. Thanks in advance!



Solution 1:[1]

How does your code even compile? You have static reference in non-static env:

... new File(getClass().getResource ...

try to get the bytearray before transforming into string:

try {
    byte[] tmpba = Files.readAllBytes(Paths.get("templates/temp.txt"));
    String s = new String(tmpba);
    
    System.out.println(s);
}catch(Exception e){
    e.printStackTrace();
}

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