0

So i have 2 Files in the same Folder. "example.csv" and "example.jpg" but when i run this code, I get the path for example.jpg but loading the example.csv throws a Nullpointer.

System.out.println(this.getClass().getResource("/example.csv").getFile());
System.out.println(this.getClass().getResource("/example.jpg").getFile());

Thx for any help

Johannes Zahn
  • 13
  • 1
  • 4
  • What is the exact error with stack trace? Have you done any debugging? – Carcigenicate Aug 30 '17 at 19:22
  • Are you sure the preceding `/` to the filename is necessary? – SHG Aug 30 '17 at 19:25
  • 1
    Duplicate of https://stackoverflow.com/questions/2593154/get-a-resource-using-getresource or https://stackoverflow.com/questions/2343187/loading-resources-using-getclass-getresource/41781868#41781868 – geneSummons Aug 30 '17 at 20:46
  • This question was closed as duplicate of the *wrong* question. It *is* a duplicate, but not of `What is a NullPointerException` – Panagiotis Kanavos Sep 01 '17 at 08:22

3 Answers3

1

I have placed .csv file in my class path and reading the file in static method. So please change according to your need, however you should be able to read the file by doing so.

InputStream inputStream = ReadFile.class.getResourceAsStream("User.csv");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
if (inputStream != null) {  
    System.out.println(" read csv file : "+reader.readLine());
}
Mad-D
  • 4,479
  • 18
  • 52
  • 93
1

Calling getFile() is futile. getResource() returns a URL within the JAR file. It isn't a file, and can't be treated as one. You can get the InputStream directly from the URL, or from getResourceAsStream() directly.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

The getResource method searches using the class loader, so:

You need to place your files in the same directory as your class files, or specify the directory relative to that directory. The code below requires them in the class files directory.

For placing them in the class files directory, remove the "/" from the file name.

System.out.println(this.getClass().getResource("example.csv").getFile());
System.out.println(this.getClass().getResource("example.jpg").getFile());
Charles Knell
  • 342
  • 1
  • 7