15

I have a Java project and I want to include a text file with the executable jar. Right now the text file is in the default package.

InputFlatFile currentFile = new InputFlatFile("src/theFile.txt");

I grab the file with that line as you can see using src. However this doesn't work with the executable jar.

How to keep this file with the executable jar, so someone using the program can just click a single icon and run the program?

peterh
  • 11,875
  • 18
  • 85
  • 108
Jake
  • 153
  • 1
  • 1
  • 4
  • 2
    You can use getResourceAsStream (http://java.sun.com/javase/7/docs/api/java/lang/ClassLoader.html#getResourceAsStream%28java.lang.String%29). See http://stackoverflow.com/questions/574809/java-load-a-resource-contained-in-a-jar among other questions. – Matthew Flaschen Apr 20 '10 at 00:36

2 Answers2

8

you want it IN the executable jar? then to read the file you should use

getClass().getResourceAsStream()

to read the file.

Keep the text file in the package you want to access it from. The classloader will find it.

Remember also that filenames in JARs are case sensitive.

Sanjay Manohar
  • 6,920
  • 3
  • 35
  • 58
7

The base directory in the jar file is in the classpath.

Try InputFlatFile currentFile = new InputFlatFile("theFile.txt");

You are probably using an IDE and it has a src folder in it that the IDE uses for the base of the packages. When you create the jar file from the IDE it then removes the src folder and the root folder has the packages in it.

i.e. in eclipse src/com.blah.blah once jar file is created the structure becomes com.blah.blah

Of course I assume that InputFlatFile is properly reading the value.

http://www.devdaily.com/blog/post/java/read-text-file-from-jar-file

Romain Hippeau
  • 24,113
  • 5
  • 60
  • 79
  • Thanks, that link helped me figure it out! – Jake Apr 20 '10 at 02:19
  • 1
    wish it worked for me. I have two files in the 'root' of the jar file and I get an error on securityProps.setProperty("javax.net.ssl.trustStore","CDAtruststore.jks"); The error is that 'the system cannot find the file specified' But the files are there at the top level inside the jar. Has mystified me for hours. – Brian Reinhold Nov 27 '12 at 14:03