환영합니다. Java 파일 압축 풀기 예제에 오신 것을 환영합니다. 지난 게시물에서는 자바에서 파일과 디렉토리를 압축하는 방법을 배웠으며, 여기서는 동일한 디렉토리에서 생성된 zip 파일을 다른 출력 디렉토리로 푸는 방법에 대해 알아보겠습니다.
Java 파일 압축 풀기
zip 파일을 풀려면 ZipInputStream
으로 zip 파일을 읽은 다음 모든 ZipEntry
를 하나씩 읽어야 합니다. 그런 다음 FileOutputStream
을 사용하여 파일 시스템에 기록해야 합니다. 또한 출력 디렉토리를 생성해야 하며, zip 파일에 있는 중첩된 디렉토리가 있는 경우 이를 만들어야 합니다. 다음은 이전에 생성된 tmp.zip
을 출력 디렉토리로 푸는 Java 파일 압축 풀기 프로그램입니다.
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);
// 출력 디렉토리 생성 (존재하지 않는 경우)
if(!dir.exists()) dir.mkdirs();
FileInputStream fis;
// 파일에서 데이터를 읽고 쓰기 위한 버퍼
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());
// 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();
// 이 ZipEntry 닫기
zis.closeEntry();
ze = zis.getNextEntry();
}
// 마지막 ZipEntry 닫기
zis.closeEntry();
zis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
프로그램이 완료되면 출력 폴더에 동일한 디렉토리 계층 구조로 모든 zip 파일 내용이 포함됩니다. 위 프로그램의 출력은 다음과 같습니다:
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
이상으로 자바 파일 압축 풀기 예제에 대해 모두 다루었습니다.
Source:
https://www.digitalocean.com/community/tutorials/java-unzip-file-example