1

I'm struggling to reference a .dat file in my java project in Eclipse. My file structure looks like this:

enter image description here

I'm trying to reference 'GeoIPLite.dat' from my 'LookupCountry.java' file. When I say "Reference" I actually mean just getting a String object of the path and then sending that as a parameter to a class that is located under the 'Referenced Libraries' in a jar.

My code in LookupCountry.java is as follow:

try{
    String dbFile = "../resources/GeoIPLite.dat"
    
    // TRIED ALL THESE AS WELL:
    //String dbFile = "/../resources/GeoIPLite.dat"
    //String dbFile = "/resources/GeoIPLite.dat"
    //String dbFile = "resources/GeoIPLite.dat"
    
    //Some more code calling the jar file......

}catch(IOException e){
    //Handles exception
}

So basically I get a IOException that gets thrown from the jar saying that the path to the .dat file is incorrect.

Any ideas??

Community
  • 1
  • 1

2 Answers2

0

In Eclipse, for example, when you run a class, you configure it as to where the 'current folder' is. From the menu: Run > Run Configuration ... and select the one you are using.

Then click the 'Arguments' tab and check the working directory.

enter image description here

Your path should be relative to the location shown there. (In the clipped image it shows the default which is the base folder of the project itself.)

You would open the file as new File("resources/GeoIPLite.dat") with the default working directory.

Lee Meador
  • 12,829
  • 2
  • 36
  • 42
0

Use the same package structure in your resource folder as you did in your src folder. Add your resource folder as a source folder in Eclipse (see screenshot). Place the .dat file, in the resource folder, relative to the class that is going to use it. You should see your resource files then along side your compiled classes.

In your code, reference the resource file like so:

this.getClass().getResource("foo.txt");

enter image description here

martinez314
  • 12,162
  • 5
  • 36
  • 63
  • When you say "same package structure". Do you mean that the 'resource' folder should also contain a package com.deangrobler which in turn contains the .dat file? –  Feb 19 '13 at 17:28
  • Yes. `getResource()` will return a URL. – martinez314 Feb 19 '13 at 17:28
  • OP never did say how he is opening the file. It could be a new `File(string)` or as `this.getClass().getResourceAsStream(string)` and the needed path would be different. You are describing what to do in the latter case. – Lee Meador Feb 19 '13 at 17:56