Retrieving a file from a jar file

Retrieving a file from a jar file

JAR file in Java is a compressed format and is used for packaging of the deliverables. At times, you may want to manipulate this file.
Below example indicates a scenario for the same.

import java.util.jar.*;

public class RetrievingJarEntry
   public static void main(String args[])
      RetrievingJarEntry retrievingJarEntry = new RetrievingJarEntry();
   private void proceed()
      String sourceJarFile = “files/contacts.jar”;
      String sourceFile = “2.txt”;
      String destFile = “files/new2.txt”;
         JarFile jarFile = new JarFile(sourceJarFile);
         JarEntry jarEntry = jarFile.getJarEntry(sourceFile);
         System.out.println(“Found entry: ” + jarEntry);
         if ( jarEntry != null)
            //Getting the jarEntry into the inputStream
            InputStream inputStream = jarFile.getInputStream(jarEntry); 
            //Creating a output stream to a new file of our choice
            FileOutputStream fileOutputStream = new;
            System.out.println(“Attempting to create file: ” + destFile);
            while (inputStream.available()  0) 
            System.out.println(“Created file: ” + destFile);
      }catch(IOException ioe)
         System.out.println(“Exception: ” + ioe);


Expected output:

[root@mypc]# java RetrievingJarEntry
Found entry: 2.txt
Attempting to create file: files/new2.txt
Created file: files/new2.txt


//Please note: You have to create a folder with name files and a jar file contacts.jar which has files 1.txt, 2.txt and 3.txt


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist