dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Retrieving a File from a Jar File

Learn how to retrieve needed files from a JAR file.


advertisement

A 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.

The example below indicates a scenario for this.

import java.util.jar.*;
import java.io.*;

public class RetrievingJarEntry
{
   public static void main(String args[])
   {
      RetrievingJarEntry retrievingJarEntry = new RetrievingJarEntry();
      retrievingJarEntry.proceed();
   }
   
   private void proceed()
   {
      String sourceJarFile = "files/contacts.jar";
      String sourceFile = "2.txt";
      String destFile = "files/new2.txt";
      try{
         
         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 java.io.FileOutputStream(destFile);
            System.out.println("Attempting to create file: " + destFile);
            while (inputStream.available()  0) 
            {  
               fileOutputStream.write(inputStream.read());
            }
            System.out.println("Created file: " + destFile);
            fileOutputStream.close();
            inputStream.close();
         }
      }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 the name files and a jar file contacts.jar that has files 1.txt, 2.txt and 3.txt.

 

Visit the DevX Tip Bank

 



   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Thanks for your registration, follow us on our social networks to keep up-to-date