import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
#java에서 지원하는 ZipEntry, zipOutputStream 을 사용 하면 경로 내의 디렉토리명, 파일명에서 한글을 사용할경우 깨지는 현상이 발생.

jazzlib 라이브러리를 사용하면 한글깨짐 문제가 해결됩니다.
import net.sf.jazzlib.ZipEntry;
import net.sf.jazzlib.ZipOutputStream;

jazzlib 는 http://jazzlib.sourceforge.net 여기에서 다운로드 할수있습니다.
또는 아래에서 다운 하세요.

jar 파일 :
 
 

 

아래 내용 출처 :
http://cafe.naver.com/itmecca.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=1737

###################### ZipUtils.java ######################

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import net.sf.jazzlib.ZipEntry;
import net.sf.jazzlib.ZipInputStream;
import net.sf.jazzlib.ZipOutputStream;

/**
* FileName : ZipUtils.java
* Comment  : # 인자값 내용
   # createZipFile(압축할디렉토리위치, 저장될zip파일의 경로를 포함한파일명, 디렉토리 없을시 생성여부)
*/
public class ZipUtils {
    private static final byte[] buf = new byte[1024];
    
    /**
    * Comment  : 생성될 ZIP파일의 경로에 디렉토리가 없을경우 에러  발생
    */
    public static void createZipFile(String targetPath, String zipPath)throws Exception{
        createZipFile(targetPath, zipPath, false);
    }
    
    /**
    * Comment  : zip 파일을 생성.
    */
    public static void createZipFile(String targetPath, String zipPath, boolean isDirCre)throws Exception{
        File fTargetPath = new File(targetPath);
        File[] files = null;
        
        if(fTargetPath.isDirectory()){
            files = fTargetPath.listFiles();
        }else{
            files = new File[1];
            files[0] = fTargetPath;
        }
        
        File path = new File(zipPath);
        File dir = null;
        dir = new File(path.getParent());
        if(isDirCre){
            dir.mkdirs();
        }
        
        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(path));
        
        // zip 파일 압축
        makeZipFile(files, zipOut, "");
        
        // stream을 닫음으로서 zip 파일 생성
        zipOut.close();
        
    }
    
    
    /**
    * Comment  : # 일부 파일들을 배열로 설정하여 zip 파일 생성
    * ex) String[] arrZip = new String[]{"C:\\aaa.txt", "C:\\bbb.txt", "C:\\ccc.txt"}
    *     ZipUtils.createZipFile(arrZip, "C:\\test.zip");
    */
    public static void createZipFile(String[] targetFiles, String zipPath)throws Exception{
        createZipFile(targetFiles, zipPath, false);
    }
    
    /**
    * Comment  : # 일부 파일들을 배열로 설정하여 zip 파일 생성 (디렉토리 생성여부 선택)
    */
    public static void createZipFile(String[] targetFiles, String zipPath, boolean isDirCre)throws Exception{
        File[] files = new File[targetFiles.length];
        for(int i = 0; i < files.length; i++){
            files[i] = new File(targetFiles[i]);
        }
        
        File path = new File(zipPath);
        File dir = null;
        dir = new File(path.getParent());
        if(isDirCre){
            // 디렉토리가 없을경우 생성
            dir.mkdirs();
        }
        
        // zip 파일의 outputStream
        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(path));
        
        // zip 파일 압축
        makeZipFile(files, zipOut, "");
        
        // stream을 닫음으로서 zip 파일 생성
        zipOut.close();
    }
    
    
    /**
    * Comment  : zip 파일의 압축을 해제
    */
    public static void unZipFile(String targetZip, String completeDir)throws Exception{
        unZipFile(targetZip, completeDir, false);
    }    
    
    /**
    * Comment  :
    */
    public static void unZipFile(String targetZip, String completeDir, boolean isDirCre)throws Exception{
        ZipInputStream in = null;
        
        try{
            File fCompleteDir = null;
            fCompleteDir = new File(completeDir);
            if(isDirCre){
                // 디렉토리가 없을경우 생성
                fCompleteDir.mkdirs();
            }
            
            // zip 파일의 input stream을 읽어들임
            in = new ZipInputStream(new FileInputStream(targetZip));
            ZipEntry entry = null;
            
            // input stream내의 압축된 파일들을 하나씩 읽어들임.
            while((entry = in.getNextEntry()) != null){
                System.out.println("entry : " + entry);
                // zip 파일의 구조와 동일하게 가기위해 로컬의 디렉토리 구조를 만듬.
                String entryName = entry.getName();
                if(entry.getName().lastIndexOf("/") > 0){
                    String mkDirNm = entryName.substring(0, entryName.lastIndexOf("/"));
                    System.out.println("mkDirNm : " + mkDirNm);
                    new File(completeDir + mkDirNm).mkdirs();
                }
                // 해제할 각각 파일의 output stream을 생성
                FileOutputStream out = new FileOutputStream(completeDir + entry.getName());
                
                int bytes_read;
                while((bytes_read = in.read(buf)) != -1){
                    System.out.println("bytes_read : " + bytes_read);
                    out.write(buf, 0, bytes_read);
                }
                // 하나의 파일이 압축해제됨
                out.close();
            }
        }catch(Exception e){
            throw new Exception(e);
        }finally{
            // 모든 파일의 압축이 해제되면 input stream을 닫는다.
            in.close();
        }
    }
    
    // byte 배열을 받아서 압축된 byte배열을 리턴
    public static byte[] compressToZip(byte[] src)throws Exception{
        byte[] retSrc = null;
        ByteArrayOutputStream baos = null;
        
        try{
            // zip 파일의 output Stream
            ByteArrayInputStream bais = new ByteArrayInputStream(src);
            baos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(baos) ;
            
            zos.putNextEntry(new ZipEntry("temp.tmp"));
            
            int bytes_read = 0;
            // 전달받은 src를 압축하여 파일에 씀
            while((bytes_read = bais.read(buf)) != -1){
                zos.write(buf, 0, bytes_read);
            }
            bais.close();
            zos.close();
            
            // 스트림을 닫은후 byte배열을 얻어옴
            retSrc = baos.toByteArray();
        }catch(Exception e){
            throw new Exception(e);
        }finally{
            baos.close();
        }
        
        return retSrc;
    }
    
    // 압축된 byte 배열을 받아서 zipPath위치에 zip 파일을 생성한다.
    private static void makeZipFile(byte[] src, String zipPath)throws Exception{
        FileOutputStream fos = null;
        ByteArrayInputStream bais = null;
        
        try{
            fos = new FileOutputStream(zipPath);
            bais = new ByteArrayInputStream(src);
            
            int bytes_read = 0;
            while((bytes_read = bais.read(buf)) != -1){
                fos.write(buf, 0, bytes_read);
            }
            
        }catch(Exception e){
            throw new Exception(e);
        }finally{
            fos.close();
            bais.close();
        }
    }
    
    // 압축된 byte 배열의 압축을 해제하여 byte배열로 리턴
    public static byte[] unZip(byte[] src)throws Exception{
        
        byte[] retSrc = null;
        ByteArrayOutputStream baos = null;
        ZipInputStream zis = null;
        int bytes_read = 0;
        
        try{
            zis = new ZipInputStream(new ByteArrayInputStream(src));
            baos = new ByteArrayOutputStream();
            
            zis.getNextEntry(); // entry는 하나밖에 없음을 보장
            while((bytes_read = zis.read(buf)) != -1){
                baos.write(buf, 0, bytes_read);
            }
            
            retSrc = baos.toByteArray();
        }catch(Exception e){
            throw new Exception(e);
        }finally{
            baos.close();
            zis.close();
        }
        
        return retSrc;
    }
    
    // 문자열을 압축하여 byte배열로 리턴(UTF-8)
    public static byte[] compressToZip(String src)throws Exception{
        return compressToZip(src.getBytes("UTF-8"));
    }
    
    // byte배열을 압축하여 zip 파일로 생성
    public static void srcToZipFile(byte[] src, String zipPath)throws Exception{
        byte[] retSrc = null;
        // 압축
        retSrc = compressToZip(src);
        
        // 파일로 만듬
        makeZipFile(retSrc, zipPath);
    }
    
    // byte 배열을 압축하여 zip 파일로 생성
    public static void srcToZipFile(String src, String zipPath)throws Exception{
        byte[] retSrc = null;
        
        // 압축
        retSrc = compressToZip(src.getBytes("UTF-8"));
        
        // 파일로 만듬
        makeZipFile(retSrc, zipPath);
    }
    
    // 압축된 zip파일을 해제후  byte배열로 리턴
    public static byte[] zipFileToSrc(String zipPath)throws Exception{
        byte[] retSrc = null;
        
        return retSrc;
    }
    
    public static void makeZipFile(File[] files, ZipOutputStream zipOut, String targetDir) throws Exception{
        for(int i = 0; i < files.length; i++){
            File compPath = new File(files[i].getPath());

            if(compPath.isDirectory()){
                File[] subFiles = compPath.listFiles();
                makeZipFile(subFiles, zipOut, targetDir+compPath.getName()+"/");
                continue;
            }

            FileInputStream in = new FileInputStream(compPath);
            zipOut.putNextEntry(new ZipEntry(targetDir+"/"+files[i].getName()));

            int data;

            while((data = in.read(buf)) > 0){
                zipOut.write(buf, 0, data);    
            }
            zipOut.closeEntry();
            in.close();
        }
    }
    
    public static void main(String[] arr) throws Exception{
        // 압축하기
        try {
            ZipUtils.createZipFile("D:\\02.TEMP\\backup2", "D:\\02.TEMP\\AAAA\\backup2_한글지원2.zip", true);
            //ZipUtils.unZipFile("D:\\02.TEMP\\backup2_aa.zip", "D:\\02.TEMP\\mkDirNm\\", true);
            
        /*
            // 문자열의 압축과 해제
            String str = "테스트333 데이터입니다.";
            byte[] src = str.getBytes("UTF-8");
            src = ZipUtils.compressToZip(src);
            byte[] retSrc = ZipUtils.unZip(src);
            System.out.println(new String(retSrc, "UTF-8"));
        */
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
}
04 14, 2010 18:29 04 14, 2010 18:29

Trackback URL : http://develop.sunshiny.co.kr/trackback/427

  1. 파일 압축

    Tracked from Like RadioHead 11 8, 2010 19:07 Delete

    원문 출처 : http://develop.sunshiny.co.kr/trackback/427 Java - Zip 파일 형식 압축및 압축풀기(한글깨짐방지 - jazzlib 사용) Posted 2010/04/14 18:29, Filed under: Language/JAVA import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; #java에서 지원하는 ZipEntry, zipOutputS..

  1. # 쎄룽 2010年 11月 08日 19時 02分 Delete Reply

    잘보았습니다~ 퍼가두될까용?? ^^

    1. Re: # sunshiny 2010年 11月 12日 23時 46分 Delete

      에구.
      댓글 남기신걸 이제야 봤네요^^
      네~ 당연히 괜찮죠.
      저도 다른분이 정리해놓은거 가져온거 거든요.^^;
      글 남겨주셔서 고맙습니다^^

  2. # 자근앙마 2010年 12月 21日 18時 00分 Delete Reply

    감사합니다

    1. Re: # sunshiny 2010年 12月 21日 20時 37分 Delete

      네~
      글 남겨 주셔서 고맙습니다^^

  3. # 2011年 05月 31日 17時 26分 Delete Reply

    좋은 자료 감사합니다
    담아갑니다^^

    1. Re: # sunshiny 2011年 06月 02日 09時 11分 Delete

      네 고맙습니다^^

  4. # 열혈강군 2011年 07月 20日 13時 25分 Delete Reply

    좋은글이라 담아갑니다.~ ^^ 출처도 남겼습니다. 감사해요.

    1. Re: # sunshiny 2011年 07月 21日 11時 02分 Delete

      네~
      답글 고맙습니다^^

Leave a comment

« Previous : 1 : ... 126 : 127 : 128 : 129 : 130 : 131 : 132 : 133 : 134 : ... 381 : Next »

Recent Posts

  1. Oracle - 바인드 변수에 대하여(테스트)
  2. Oracle - 디폴트 롤, DBA, CONNECT,...
  3. Oracle - 권한 및 롤 관리
  4. Oracle - SQL*PLUS의 SYSDBA 접근 제어
  5. Oracle - PFILE, SPFILE 에 관하여

Recent Comments

  1. 네 답글 고맙습니다. 좋은 한주 보... sunshiny 05 14,
  2. 좋은 정보 잘 살펴보고 갑니다. ememoho 05 12,
  3. 네. 고맙습니다^^ 행복한 한해 보... sunshiny 01 16,
  4. sunshiny님. 안녕하세요... 올려 주... yihans 01 16,
  5. 답글 주셔서 고맙습니다^^ 소스 복... sunshiny 01 11,

Recent Trackbacks

  1. 윈도우 cmd 명령어 팁 월풍도원(月風道院) - Delight on th... %M
  2. 파일 압축 Like RadioHead %M
  3. Mysql - mysql 설치후 Character set... 멀고 가까움이 다르기 때문 %M

Calendar

«   05 2012   »
    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    

Bookmarks

  1. 위키피디아
  2. MysqlKorea
  3. Oracle All Documentation
  4. 엑셈
  5. 오라클 클럽
  6. 네이버개발자센터
  7. API - Java
  8. API - Spring
  9. Java Community
  10. Reference - Spring
  11. 스프링사용자
  12. 자바소스
  13. 자바지기
  14. Ready System
  15. Solaris Freeware
  16. Linux-Site
  17. RedHat Korea
  18. 윈디하나의 솔라나라

Site Stats

TOTAL 245426 HIT
TODAY 132 HIT
YESTERDAY 139 HIT