How to read a file from a jar file?

Viewed 76381

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;
7 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();

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));
...

A Jar file is a zip file.....

So to read a jar file, try

ZipFile file = new ZipFile("whatever.jar");
if (file != null) {
   ZipEntries entries = file.entries(); //get entries from the zip file...

   if (entries != null) {
      while (entries.hasMoreElements()) {
          ZipEntry entry = entries.nextElement();

          //use the entry to see if it's the file '1.txt'
          //Read from the byte using file.getInputStream(entry)
      }
    }
}

Hope this helps.

Something similar to this answer is what you need.

You need to pull the file out of the archive in that special way.

BufferedReader input = new BufferedReader(new InputStreamReader(
         this.getClass().getClassLoader().getResourceAsStream("1.txt")));

This worked for me to copy an txt file from jar file to another txt file

public static void copyTextMethod() throws Exception{
    String inputPath = "path/to/.jar";
    String outputPath = "Desktop/CopyText.txt";

    File resStreamOut = new File(outputPath);

     int readBytes;
     JarFile file = new JarFile(inputPath);

     FileWriter fw = new FileWriter(resStreamOut);

    try{
        Enumeration<JarEntry> entries = file.entries();
        while (entries.hasMoreElements()){
            JarEntry entry = entries.nextElement();
        if (entry.getName().equals("readMe/tempReadme.txt")) {

                System.out.println(entry +" : Entry");
            InputStream is = file.getInputStream(entry);
            BufferedWriter output = new BufferedWriter(fw);
                 while ((readBytes = is.read()) != -1) {
                    output.write((char) readBytes);
                 }
                System.out.println(outputPath);
                output.close();
            } 
        }
    } catch(Exception er){
        er.printStackTrace();
    }
        }
            }
Related