본문 바로가기
C++ 200제/코딩 IT 정보

JAVA ZIP 압축파일 만들기 예제 2개, 자바 라이브러리 3개 응용

by vicddory 2018. 5. 7.

자바 ZIP 파일 압축 예제 (ZipOutputStream)


먼저 사용 방법 이론을 설명하고 이어서 예제 2개를 소개하겠습니다.


변수에 저장된 폴더와 파일 경로를 JAVA ZIP으로 압축하는 예제 소스입니다.  Java에는 라이브러리가 존재하므로 구현하긴 쉬워요. 별도로 자바 압축파일(ZIP)을 이용하기 위한 설치 파일이나 3rd party 라이브러리는 필요 없어요.


우선, Oracle에서 제공하는 자바 플랫폼 문서를 참조합니다. SE 7 버전의 기반의 문서이나 다른 버전과의 차이는 없습니다. 무슨 뜻이냐면, 자바 버전 신경쓰지 말고 그냥 쓰면 된다는 겁니다.


JAVA ZIP 압축파일 만들기 예제 2개, 자바 라이브러리 3개 응용[파일 생성 프로그래밍과 라이브러리]




많은 ZIP 압축 패키지들이 있는데 기본적으로 사용하는 패키지는 아래에 3개입니다.


  • ZipEntry
  • ZipOutputStream
  • ZipException


이 예제에서는 ZipEntry, ZipOutputStream 2개를 사용합니다.


Package Java util - ZipEntry - ZipOutputStream ZipException[파일 생성 프로그래밍과 라이브러리]


일단, 바이트 배열을 생성합니다.


JAVA FileOutputStream 오브젝트로 경로와 ZIP 파일명을 결정하고, FileInputStream 오브젝트로 압축이 될 파일을 선택합니다. 실제 압축을 위해선, FileInputStream에서 지정된 파일을 바이트 배열로 분리하여 ZIP으로 재생성이 필요한데, 이를 돕는 메소드가 ZipOutputStream입니다.


이 자바 메소드는 압축될 바이트를 하나씩 꺼내어 FileOutputStream으로 전달해 정상적으로 압축이 되도록 돕습니다. 소스는 복잡하지 않습니다. 이미 라이브러리가 지원되기 때문이죠.



자바 ZIP 압축 예제 1)


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
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import  java.util.zip.ZipEntry;
import  java.util.zip.ZipException;
import  java.util.zip.ZipOutputStream;
 
public class  ZIPex{
    public static void  main(String args[])
    {         
        try 
        {
            String zipFile = "C:/example.zip";
            String sourceFile = "C:/target.txt";
 
            byte [] buffer = new byte [1024];
            
             FileOutputStream fout = new FileOutputStream(zipFile);
             ZipOutputStream zout = new ZipOutputStream(fout);
             FileInputStream fin = new FileInputStream(sourceFile);
             zout.putNextEntry(new ZipEntry(sourceFile));
 
             int length;
 
             while((length = fin.read(buffer)) > 0)
             {
                 zout.write(buffer, 0length);
             }
 
              zout.closeEntry();
              fin.close();
              zout.close();
              System.out.println("Zip file has been created!");
        }
        catch(IOException ioe)
        {
            System.out.println("IOException :" + ioe);
        }
    }
}
cs


위 자바 코드에 조금 더 『기교를 부리면』 아래처럼 구현 할 수 있습니다. 파일 생성 코드를 절약할 수 있죠.


자바 ZIP 파일 압축 예제 (ZipOutputStream)[파일 생성 프로그래밍과 라이브러리]


자바 JAVA ZIP 압축 예제 2)


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
ZipFile zipFile = new ZipFile(file);
 
try {
    Enumeration<extends ZipEntry> entries = zipFile.entries();
    
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File entryDestination = new File(outputDir,  entry.getName());
        
        if (entry.isDirectory())
            entryDestination.mkdirs();
        else {
            entryDestination.getParentFile().mkdirs();
            InputStream in = zipFile.getInputStream(entry);
            OutputStream out = new FileOutputStream(entryDestination);
            
            IOUtils.copy(inout);
            IOUtils.closeQuietly(in);
            
            out.close();
        }
    }
finally {
    zipFile.close();
}
cs


JAVA에서 ZIP 파일 만드는 소스는 위의 2개 사용하시면 되겠습니다. 


추가로 압축 파일 생성 오류 코드도 작성해 보세요. ZipException 클래스를 사용하면 됩니다.


자바 ZIP 파일 압축 예제 (ZipOutputStream)

댓글