0

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!

sinha-shaurya
  • 549
  • 5
  • 15
  • 2
    A `java.util.File` needs to be a physical resource on the file system. Something that is packaged in a jar/war/ear isn't a physical resource on the file system. So you can only read it with an `InputStream` and not a `File`. – M. Deinum May 13 '22 at 07:35

1 Answers1

-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();
}
user3192295
  • 358
  • 2
  • 13
  • It compiles just fine. Syntactically the code snippets posted are correct . It does not throw any compilation error. As far I can see, there has been no static reference at all. The line mentioned used getResource() method – sinha-shaurya May 13 '22 at 02:32
  • This results in java.nio.file.NoSuchFileException – sinha-shaurya May 13 '22 at 03:02
  • you never mentioned you were using a packaged file. So it makes perfect sense. Thnx to @M. Deinum. – user3192295 May 13 '22 at 10:58