i have a program java swing program that reads a .txt file. When i try to make runnable jar file it cant read it. How can i make a runnable jar for such a program? thanks
2 Answers
File -> Export -> Java -> Runnable JAR file
Make sure you are setting your launch configuration for the .jar
file correctly, and that you are extracting the required libraries into the .jar
as well.
The text file is probably not being pointed to the right location in your source code. I would suggest looking into a JFileChooser
and getting the location of the selected file from that. You could also have the text file pinpointed to one directory. An example of this:
File dir = new File(System.getenv("APPDATA"), "folder");
if (dir.exists() && dir.isDirectory()) File file = new File(dir, "input.txt");
This code sets up a folder in the user's AppData
folder on their computer (Windows). The file created afterwards is then put into that folder. Using code like that, I can now read that file no matter where my .jar
file is placed, as long as input.txt
exists at that location.

- 8,057
- 9
- 41
- 81
-
FileInputStream fstream = new FileInputStream("input.txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { – mystery Apr 06 '13 at 00:13
-
Yep, with this code, `input.txt` always has to be at the same location that the `.jar` is located. See my updated answer for a possible solution. – syb0rg Apr 06 '13 at 00:15
-
Thanks, i got it. However , cant i insert this txt inside of jar? – mystery Apr 06 '13 at 00:20
-
Maybe [this](http://stackoverflow.com/questions/10452825/including-a-text-file-inside-a-jar-file-and-reading-it) could help you out. Try doing a little research on your own. This was found pretty easily by me in less than 30 seconds. – syb0rg Apr 06 '13 at 00:22
In eclipse go to file -> export -> java -> runnable jar file.
As for reading the .txt file, you can either hard code the file location in the code, or you can feed it in as argument through the command line, ie java myProgram.jar myFile.txt

- 1,032
- 2
- 8
- 16