2009년 4월 29일 수요일

자바 클래스(java.util.zip 패키지)를 이용하여 압축해 주는 소스

오늘 서버의 파일을 클라이언트의 요청에 따라서 압축하여 내려줘야 하는 일이 생겼다. 클라이언트가 C++ 기반이어서 ZIP으로 압축을 해야 하는 것이다. 그래서 웹 사이트에서 찾은 소스를 기본으로 하여 테스트 코드를 만들어둔다.

/**
 * Compress.java
 * 
 * 지정된 파일을 자바 클래스를 이용하여 압축해 주는 클래스
 * 
 */
package net.wiseant.util.compress;

/**
 * 
 */
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Compress {

 public static void main(String[] args) {
                
     // 압축할 원본 파일들
  // WINDOWS 파일 시스템을 기준으로 한 절대경로로 지정함.
     String[] source = new String[] { "D:\\java_dev\\jdk1.5.0_11\\doc\\index.html",
            "D:\\java_dev\\jdk1.5.0_11\\doc\\overview-frame.html",
            "D:\\java_dev\\jdk1.5.0_11\\doc\\overview-summary.html" };
                 
     byte[] buf = new byte[1024];
 
     try {
         String target = "D:\\java_dev\\jdk1.5.0_11\\doc\\doc.zip";
         ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(target));
 
         // source라는 문자 배열에 정의된 파일 수 만큼 파일들을 압축한다.
         for (int i = 0; i < source.length; i++) {
          FileInputStream in = new FileInputStream(source[i]);
 
             zipOut.putNextEntry(new ZipEntry(source[i]));
 
             int len;
             while ((len = in.read(buf)) > 0) {
              zipOut.write(buf, 0, len);
             }

             zipOut.closeEntry();
             in.close();
         }

         zipOut.close();
     } catch (IOException e) {
     }
    }

}

댓글 없음: