달력

32024  이전 다음

  • 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

자바로 zip 파일을 다룰때(압축 풀기/압축하기) 영문이름으로 된 파일은 정상적으로 잘 되지만

한글이름으로된 파일을 다룰때에는 Exception이 발생한다.

간단하게 예제를 살펴보자.


import java.io.File;
import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;


public class ZipTest {

    public static void main(String[] args) throws Exception {
        File file = new File("e:/교육자료/이클립스단축키.zip");
        ZipInputStream in = new ZipInputStream(new FileInputStream(file));
        ZipEntry entry = null;
        while((entry = in.getNextEntry()) != null ){
            System.out.println(entry.getName()+" 파일이 들어 있네요.");
        }
    }

}


위 예제는 이클립스단축키.zip 라는 zip 파일안에 어떤 파일들이 압축되어 있는지 단순하게 리스트를 출력해보는 프로그램이다. 이클립스단축키.zip 파일안에는 다음과 같은 파일 2개가 압축되어 있다.

Keyboard_shortcuts.pdf

이클립스단축키.txt


이 프로그램을 실행시켜보면 아래와 같은 에러가 발생한다.


Keyboard_shortcuts.pdf 파일이 들어 있네요.
java.lang.IllegalArgumentException
 at java.util.zip.ZipInputStream.getUTF8String(ZipInputStream.java:284)
 at java.util.zip.ZipInputStream.readLOC(ZipInputStream.java:237)
 at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:73)
 at ZipTest.main(ZipTest.java:29)
Exception in thread "main"


[Keyboard_shortcuts.pdf] 파일명을 처리할때는 문제가 없다가 [이클립스단축키.txt] 처럼 한글이름으로 된 파일명을 다룰때는 Exception 이 발생함을 알 수 있는데, 이문제는 java.util.zip 패키지의 한글처리 인코딩로직의 버그이다. 하지만 한글 인코딩 문제는 의외로 아주 간단하게 해결된다.


Jochen Hoenicke 가 만든 jazzlib.jar 라이브러리를 다운받아 클래스패스에 추가하면 된다. 소스는 전혀 수정할 필요가 없고 단지 import 문만 아래와 같이 수정해 주면 된다.


import java.io.File;
import java.io.FileInputStream;
import net.sf.jazzlib.ZipEntry;
import net.sf.jazzlib.ZipInputStream;


public class ZipTest {

    public static void main(String[] args) throws Exception {
        File file = new File("e:/교육자료/이클립스단축키.zip");
        ZipInputStream in = new ZipInputStream(new FileInputStream(file));
        ZipEntry entry = null;
        while((entry = in.getNextEntry()) != null ){
            System.out.println(entry.getName()+" 파일이 들어 있네요.");
        }
    }

}


다시 프로그램을 실행시켜 보면 아래와 같이 정상적인 결과를 확인할 수 있다.

Keyboard_shortcuts.pdf 파일이 들어 있네요.
이클립스단축키.txt 파일이 들어 있네요.


jazzlib.jar 파일은 인코딩 문제를 해결한 라이브러리이므로 압축할때와 압축을 풀때 모두 잘 작동한다.


Reference is jazzlib

Posted by tornado
|