How would you read a file into a program that's compiled into a jar next to it through its local directory? The type read would be a simple .txt file.
2 Answers
It depends on what the usage of the program is. Do you know how the jar is supposed to be executed? When you try to run it, does it spit out a "usage: somejar firstarg secondarg" type message?
Also, if its a jar that you've compiled and you know how it should be executed, then you may have forgot to set its main class or manifest.
Check this: http://www.mkyong.com/java/how-to-make-an-executable-jar-file/

- 5,229
- 3
- 31
- 46
If you want to read a file that exists within an external .jar file, you will need to unzip the .jar file first in your code and then retrieve the file. You can do this using Java's zip APIs. See this answer if this is the case: Easiest way to unpack a jar in java
If you want to read a file that is in the same .jar file that your code is executing, you can get the file as a resource. See this answer: Get a resource using getResource()
If the file is simply in the exact same directory as the executable .jar, create a new file like so:
File input = new File("myfile.txt");

- 1
- 1

- 2,558
- 1
- 16
- 24
-
I meant if your program is a runnable jar and you have a file sitting next to it while both of them are in the same folder. – Killam Oct 30 '13 at 02:07
-
1If you just need to read an external file that is not packaged in a jar, simply create a new file and pass the name of the file. See my edit. – hotforfeature Oct 30 '13 at 02:10