Decompress the ZIP file using zipfile in Java code

Source: Internet
Author: User

Use the java.util.zip. zipfile class to decompress the file.

You can decompress the zip, jar, and war files, but cannot decompress the rarfile.

import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.util.Enumeration;import java.util.zip.ZipEntry;import java.util.zip.ZipFile;public class UnZip {static final int BUFFER = 1024;public void unzip(File unZipDir, File zip) throws IOException {if (!zip.exists()) {return;}if (!unZipDir.exists()) {unZipDir.mkdirs();}if (!unZipDir.isDirectory()) {return;}    int fileCount = 0;ZipFile zipfile = new ZipFile(zip);BufferedOutputStream ds = null;BufferedInputStream is = null;ZipEntry entry = null;Enumeration entries = zipfile.entries();System.out.println("Start...");while (entries.hasMoreElements()) {try {entry = (ZipEntry) entries.nextElement();System.out.println((++fileCount)+") Extracting: " + entry);File tempFile = new File(unZipDir.getAbsolutePath() + "/"+ entry.getName());if(entry.isDirectory()){tempFile.mkdirs();continue;} else if (!tempFile.getParentFile().exists()) {tempFile.getParentFile().mkdirs();}is = new BufferedInputStream(zipfile.getInputStream(entry));int count;byte data[] = new byte[BUFFER];FileOutputStream fos = new FileOutputStream(unZipDir.getAbsolutePath()+ "/" + entry.getName());ds = new BufferedOutputStream(fos, BUFFER);while ((count = is.read(data, 0, BUFFER)) != -1) {ds.write(data, 0, count);}ds.flush();} catch (IOException ex) {throw ex;} finally {try {if (ds != null)ds.close();if (is != null)is.close();} catch (IOException e) {// ignore}}}System.out.println("Finished !");}public static void main(String[] args) {UnZip unZip = new UnZip();try {unZip.unzip(new File("C:/unzip/"), new File("C:/StockQuote1.war"));} catch (Exception e) {e.printStackTrace();}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.