skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Friday, November 2, 2012

Extract a zip file in Java

Posted by Raju Gupta at 3:48 AM – 0 comments
 

The sole purpose of this program is how to extarct the content of a zip file in java.We start by opening an input stream to the compressed file and an output stream to the file where we want the content to be extracted.
After that we get the next entry of the zip file (and the only entry in this case) - test so it's not null, and then start reading the contents from the input stream and writing each chunk read to the output stream.
As usual we should clean up properly afterwards so we close the input and output streams.


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
 
public class ExtractingZipFile{
 
    /**
     * Extracts a zip file
     */
    public void extractZipFile() {
         
        try {
            String zipFileName = "file.zip";
            String extractedFileName = "extractedfile.txt";
             
            //Create input and output streams
            ZipInputStream inStream = new ZipInputStream(new FileInputStream(zipFileName));
            OutputStream outStream = new FileOutputStream(extractedFileName);
             
            ZipEntry entry;
            byte[] buffer = new byte[1024];
            int nrBytesRead;
             
            //Get next zip entry and start reading data
            if ((entry = inStream.getNextEntry()) != null) {
                while ((nrBytesRead = inStream.read(buffer)) > 0) {
                    outStream.write(buffer, 0, nrBytesRead);
                }
            }
                     
            //Finish off by closing the streams
            outStream.close();
            inStream.close();
             
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
     
     
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new ExtractingZipFile().extractZipFile();
    }
     
}

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger