Sam Sam - 7 months ago 24
Java Question

How to read a file from a jar file?

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

You can't use File, since this file does not exist independently on the file system. Instead you need getResourceAsStream(), like so:

...
InputStream in = getClass().getResourceAsStream("/1.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(in));
...