How to read a file from a jar file?

Freeman picture Freeman · Feb 16, 2010 · Viewed 69.9k times · Source

I have a file in a JAR file. It's 1.txt, for example.

How can I access it? My source code is:

Double result=0.0;
File file = new File("1.txt")); //how get this file from a jar file
BufferedReader input = new BufferedReader(new FileReader(file));
String line;
while ((line = input.readLine()) != null) {
  if(me==Integer.parseInt(line.split(":")[0])){
    result= parseDouble(line.split(":")[1]);
  }
}
input.close();
return result;

Answer

Bozho picture Bozho · Feb 16, 2010

If your jar is on the classpath:

InputStream is = YourClass.class.getResourceAsStream("1.txt");

If it is not on the classpath, then you can access it via:

URL url = new URL("jar:file:/absolute/location/of/yourJar.jar!/1.txt");
InputStream is = url.openStream();