1

I have a java project which should read file in a external folder. I give the file path as '../FolderName' in the class. But if I generated a jar file from this project, it cannot read the file. What is the correct way to define the folder path in this kind of situations ?

  • 1
    You can provide some code you have written so far, the name of the jar, and maybe a location inside the project or filesystem. Do you have problems with other jars/zips, or only with those built in netbeans? – Javier Aug 03 '15 at 11:24
  • [Load Icon Image Exception](http://stackoverflow.com/q/9864267/1393766) <- rule applies to all resources, not only images – Pshemo Aug 03 '15 at 11:36

3 Answers3

2

You should use java.lang.Class.getResourceAsStream(String).

It reads the file from inside your JAR.

Example:

InputStream in = getClass().getResourceAsStream("/classpath/to/my/file");
BufferedReader input = new BufferedReader(new InputStreamReader(in));

A good Reference : How to read a file from a jar file?

Community
  • 1
  • 1
rhitz
  • 1,892
  • 2
  • 21
  • 26
0

The correct way to pass the absolute path to your code (jar) as program argument.

java -jar myjar.jar abs_path

You can then access the absolute path in the main() method of your class (mentioned in the manifest.mf file of a JAR) as follows:

String filePath = args[0];
aviad
  • 8,229
  • 9
  • 50
  • 98
0
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("/classpath/toyourfile");
Sandeep Bhardwaj
  • 1,310
  • 1
  • 18
  • 24