0
  • I'm working on a Java program in Netbeans that I'd like to be able to run from an external jar file
  • And I cannot seem to read from a file that isn't located inside of the project default directory or some subfolder located there, and that only works inside Net beans.
  • What I'd like to be able to do is read the text file from the file path

src/assets/files/textFile.txt

.

I've tried all of the suggestions here, but they don't seem to work for me. Here's the code I'm currently using:

File file = new File("assets/files/textFile.txt");
if (!file.exists()) {
    throw new FileNotFoundException("File does not exist");
}
FileReader fr = new FileReader(file.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);

When I try to run this, the exception is thrown each time.

Community
  • 1
  • 1
Dusk
  • 1
  • 1
  • Duplicate from http://stackoverflow.com/questions/3369794/how-to-read-a-file-from-jar-in-java – Nadir Apr 12 '16 at 09:46
  • `assets/files` should be in your resource path and you should look up a unitInfo.txt resource with your ClassLoader. – Aaron Apr 12 '16 at 09:46
  • It depends on whether your file is within your classpath or not. If is is not you have to provide its full path. – m c Apr 12 '16 at 09:47
  • @Aaron the unitInfo.txt was a misname from a copy/paste of mine, I changed the names here to textFile.txt for more genericness, I've edited my post for that. – Dusk Apr 12 '16 at 09:51
  • http://www.mkyong.com/java/java-read-a-file-from-resources-folder/ – titogeo Apr 12 '16 at 09:52
  • I can't edit my comment anymore, but I guess you get the point? It's the same solution provided by Nadir's linked answer. – Aaron Apr 12 '16 at 09:52
  • @madveshonok117 The class that this code is from is inside of the assets package, where the files folder is . I've tried to use just "files/textFile.txt", but that also doesn't work. – Dusk Apr 12 '16 at 09:54

1 Answers1

0

The term for such non-Files is resource.

String encoding = "UTF-8";
new BufferedReader(
    new InputStreamReader(YourClass.getResourceAsStream("/assets/files/textFile.txt"),
        encoding));

Also FileReader is an old utility class that uses the default system encoding. That might be different from where the text file was created, hence Unicode, such as encoded in UTF-8, would be ideal. For Windows users you might write a BOM character at the beginning to mark the file as UTF-8: "\ufeff".

The class YourClass should be from the jar. Here an absolute path is used "/...". A relative path would start with the package path.

Also Windows is not case-sensitive. Other systems and the zip format of the jar are case-sensitive. Check the jar with a zip utility for correct paths.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138