Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 
like image 642
Freeman Avatar asked Feb 16 '10 09:02

Freeman


People also ask

Can we extract files from jar?

To unpackage a JAR, you need a program that can extract compressed files. Windows includes functionality for this, but you can also use file extraction software like 7-Zip or WinRAR to get the job done. Open the JAR file within the software, and you can browse all the folders and files within it.

How do I unpack a JAR file?

Select “File,” then click “Open Archive” to open your JAR file, or click the “Open” icon. Browse to find the file's location, select it, and then click “Open.”


1 Answers

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(); 
like image 68
Bozho Avatar answered Sep 19 '22 02:09

Bozho