Chào mừng bạn đến với hướng dẫn giải nén tệp ZIP trong Java. Trong bài đăng trước, chúng ta đã học cách nén tệp và thư mục trong Java, tại đây chúng ta sẽ giải nén cùng một tệp ZIP được tạo từ thư mục vào một thư mục đầu ra khác.
Giải nén tệp Zip trong Java
Để giải nén một tệp ZIP, chúng ta cần đọc tệp ZIP bằng ZipInputStream
và sau đó đọc tất cả các ZipEntry
lần lượt từng cái một. Sau đó sử dụng FileOutputStream
để ghi chúng vào hệ thống tệp. Chúng ta cũng cần tạo thư mục đầu ra nếu nó không tồn tại và bất kỳ thư mục lồng nhau nào có trong tệp ZIP. Dưới đây là chương trình giải nén tệp Java sẽ giải nén tệp tmp.zip
đã tạo trước đó vào thư mục đầu ra.
package com.journaldev.files;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipFiles {
public static void main(String[] args) {
String zipFilePath = "/Users/pankaj/tmp.zip";
String destDir = "/Users/pankaj/output";
unzip(zipFilePath, destDir);
}
private static void unzip(String zipFilePath, String destDir) {
File dir = new File(destDir);
// create output directory if it doesn't exist
if(!dir.exists()) dir.mkdirs();
FileInputStream fis;
//buffer for read and write data to file
byte[] buffer = new byte[1024];
try {
fis = new FileInputStream(zipFilePath);
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry ze = zis.getNextEntry();
while(ze != null){
String fileName = ze.getName();
File newFile = new File(destDir + File.separator + fileName);
System.out.println("Unzipping to "+newFile.getAbsolutePath());
//create directories for sub directories in zip
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
//close this ZipEntry
zis.closeEntry();
ze = zis.getNextEntry();
}
//close last ZipEntry
zis.closeEntry();
zis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Khi chương trình hoàn tất, chúng ta sẽ có tất cả nội dung của tệp zip trong thư mục đầu ra với cùng một cấu trúc thư mục. Dưới đây là đầu ra của chương trình trên:
Unzipping to /Users/pankaj/output/.DS_Store
Unzipping to /Users/pankaj/output/data/data.dat
Unzipping to /Users/pankaj/output/data/data.xml
Unzipping to /Users/pankaj/output/data/xmls/project.xml
Unzipping to /Users/pankaj/output/data/xmls/web.xml
Unzipping to /Users/pankaj/output/data.Xml
Unzipping to /Users/pankaj/output/DB.xml
Unzipping to /Users/pankaj/output/item.XML
Unzipping to /Users/pankaj/output/item.xsd
Unzipping to /Users/pankaj/output/ms/data.txt
Unzipping to /Users/pankaj/output/ms/project.doc
Vậy là bạn đã nắm được toàn bộ ví dụ về cách giải nén tệp Zip trong Java.