views:

163

answers:

2

I wrote a program that is based completely on a single text file: I read the file, store the information, then search the information, etc. So, for the program to work, the file just has to be present and detectable by the program. I use eclipse, so I put the file is in the default resources map (src/main/resources). At the start of my program I create the file:

private static File textFile = new File("src/main/resources/TEXT.TXT")

However, when I try to package my program using Maven, I get a JAR in which all class and resources files are present in the same folder; my program stops working since it cannot find the file anymore.

Any help on how to deal with this problem? I`d prefer a situation in which my program works in eclipse and as a JAR, but as a JAR only would be alright as well.

+3  A: 

You can use ClassLoader.getResourceAsStream to load it from the classpath (or getResource to get the URL of the file).

Thread.currentThread().getContextClassLoader().getResource("TEXT.TXT")

This works as long as src/main/resources is on the classpath in eclipse. (The maven eclipse plugin includes it by default.) The file has to be in the jar file to work outside of eclipse.

Thomas Jung
Alternatively, getClass().getClassLoader().getResource("TEXT.TST") which is safer in some environments since you will always get the classloader that your code came from.
Francis Upton
A: 

Nice suggestions, this works perfect in eclipse itself: the correct location of the file is returned and I can use the file to do whatever I like. When opening the program as a jar, there is still a problem. The getResource method returns a location that looks like the right one:

/something/something/something/something/workspace/program/target/program-0.0.1.jar!/TEXT.TXT.

However, when I convert this url to a string, use that string to create a file object and use this file object in my program, I get the following error:

java.io.FileNotFoundException: file:/something/something/something/something/workspace/program/target/program-0.0.1.jar!/TEXT.TXT (No such file or directory)

So, the getResource method does find the file, but the program somehow can't use it..

RvdLee