views:

35

answers:

3

Hi,

My Java program references a lot of data files. I put them in a top level directory called data/, along with src/ and bin/. In Eclipse, references to data/ and ../data/ both seem to work. When I run it from the command line, only ../data/ works.

When I put the bin/ and data/ directories in a jar and correctly set the entry point, it doesn't seem to know that I want it to access the data/ directory inside the jar. The only way I've been able to get it to work is by setting the references to ../data/ and placing the jar in the bin directory. This obviously doesn't do me any good, because it's not self-contained.

What do I need to do to the references to make them work?

Thanks

+2  A: 

I'd recommend you access the files in a classpath-relative way, whether in Eclipse or in a compiled JAR.

There are a few ways you might go about it, but a basic JDK-only approach would be to use Class's getResourceAsStream() method, giving you access to an InputStream object that you can read in.

RonU
+1  A: 

If your resources are in a jar file, consider using this method to read them:

class Class {
    InputStream getResourceAsStream(String name)
}

This looks for the resource relative to a class (which may be in a jar), rather than relative to the working directory.

Andy Thomas-Cramer
A: 

Thanks for pointing me down this path, guys. I ended up doing a really hacked up workaround because I'm not very good with IO yet. I used getClass() to construct a URL:

http://forums.sun.com/thread.jspa?threadID=5258488

Then made a new File object from this string (new File(file)):

String file = url.toString().replaceFirst("file:", "");

This allowed me to keep the same code that referenced the file objects.

walrus
Edit: this will not work with jars. See: http://forum.springsource.org/archive/index.php/t-65452.html Apparently, I would have to re-do all my file-centric code (Scanner objects, etc.) to work with URLs or the like. Ah, oh well.
walrus
I warmly recommend using `Class#getResource()` / `getResourceAsStream()` instead of shooting/hacking/fiddling around in the dark like that.
BalusC