-1

I ma new to this so I am sorry if this is a stupid question. But please I need your help. I have the following directories in ecplise: Directory Hierarchy of course with a directory containing all these files.
I am trying to use get class.getResource to access a file called "data.txt" as such:

scanObj = new Scanner(new File(this.getClass().getResource("resources/data.txt").toExternalForm()));

But I am getting a null pointer exception why is that? Many thanks! Any help would be much appreciated

2 Answers2

0

First print value of

this.getClass().getResource("resources/data.txt")

to console. If it prints null then that's the cause of problem. This will mostly happen if the file that you are referring to is not on the class path. Search for posts regarding how to add files to class path in eclipse.

Rohit
  • 146
  • 1
  • 5
  • When I did that, this is what it returned : file:/C:/Users/James/Desktop/Game/Maths/bin/resources/data.txt – James Neil Dec 15 '17 at 14:02
  • So the file is not in ur class path. The method that you are using is used to get files from class path. So don't think getResource is going to work. Best way would be to get file location as input parameter and provide that parameter to file constructor. This way your code will be configurable and can accept file from any location. – Rohit Dec 15 '17 at 14:09
  • Sorry is there a way to put it into class path because I am trying to convert this into an exe jar file – James Neil Dec 15 '17 at 14:11
  • Add that file to your src folder. But remember to include that txt file while creating jar file. – Rohit Dec 15 '17 at 14:12
  • I did it add it to the src folder but still nothing, its weird because its going into the bin folder is that suppose to happen? – James Neil Dec 15 '17 at 14:39
  • Have a look at this https://stackoverflow.com/questions/2343187/loading-resources-using-getclass-getresource – Rohit Dec 15 '17 at 14:50
0

Because the lookup is relative to the working folder of the application. Check what that folder is (should be in the run configuration for your class in Eclipse), and construct the path relative to that location.

Alternatively, use ClassLoader.getSystemClassLoader().getResourceAsStream("data.txt") (this will net you the InputStream)

Alex Savitsky
  • 2,306
  • 5
  • 24
  • 30