조회 수 1710 추천 수 0 댓글 0

단축키

Prev이전 문서

Next다음 문서

수정 삭제

단축키

Prev이전 문서

Next다음 문서

수정 삭제
Extra Form
import system.log.Logger;
import system.exception.Exception;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
/**
 * Created by IntelliJ IDEA.
 * Date: 2006. 7. 6
 * Time: 오후 3:48:11
 * To change this template use File | Settings | File Templates.
 * java.util.zip에 있는 놈을 쓰게 되면 압축할 때 한글명으로 된 파일은 깨져서 들어간다..
 * 결국 그때문에 나중에 압축을 풀때 에러가 나게 된다...
 * 해서 이놈을 jazzlib 라이브러리를 사용하여 해결하였다....
 */
public class compressTest {
    static Logger logger = (Logger)Logger.getLogger();
    static final int COMPRESSION_LEVEL = 8;
    static final int BUFFER_SIZE = 64*1024;
 
    public static void main(String[] args) throws IOException {
        // 압축할 폴더를 설정한다.
        String targetDir = "D:testtestest";
        // 현재 시간을 설정한다.
        long beginTime = System.currentTimeMillis();
        int cnt;
        byte[] buffer = new byte[BUFFER_SIZE];
        FileInputStream finput = null;
        FileOutputStream foutput;
 
        /*
         **********************************************************************************
         * java.util.zip.ZipOutputStream을 사용하면 압축시 한글 파일명은 깨지는 버그가
         * 발생합니다.
         * 이것은 나중에 그 압축 파일을 해제할 때 계속 한글 파일명이 깨는 에러가 됩니다.
         * 현재 Sun의 공식 입장은 이 버그를 향후 수정할 계획이 없다고 하며
         * 자체적으로 공식적 버그라고 인정하고 있지 않습니다.
         * 이런 비영어권의 설움...ㅠ.ㅠ
         * 해서 이 문제를 해결한 net.sf.jazzlib.ZipOutputStream을 추가하오니
         * 이 라이브러리 사용을 권장하는 바입니다.
         *********************************************************************************/
        net.sf.jazzlib.ZipOutputStream zoutput;
 
        /*
         ********************************************
         * 압축할 폴더명을 얻는다. : 절대 경로가 넘어올 경우 --> 상대경로로 변경한다...
         *********************************************/
        targetDir.replace('', File.separatorChar);
        targetDir.replace('/', File.separatorChar);
        String dirNm = targetDir.substring(targetDir.lastIndexOf(File.separatorChar)+1
                                                        , targetDir.length());
        // 압축할 폴더를 파일 객체로 생성한다.
        File file = new File(targetDir);
        String filePath = file.getAbsolutePath();
        logger.debug("File Path : " + file.getAbsolutePath());
 
        /*
         **************************************************************************
         * 폴더인지 파일인지 확인한다...
         * 만약 넘겨받은 인자가 파일이면 그 파일의 상위 디렉토리를 타겟으로 하여 압축한다.
         *****************************************************************************/
        if (file.isDirectory()) {
            logger.debug("Directory.........");
        } else {
            file = new File(file.getParent());
        }
        // 폴더 안에 있는 파일들을 파일 배열 객체로 가져온다.
        File[] fileArray = file.listFiles();
 
        /*
         *****************************************************************
         * 압축할 파일 이름을 정한다.
         * 압축할 파일 명이 존재한다면 다른 이름으로 파일명을 생성한다.
         *****************************************************************/
        String zfileNm = filePath + ".zip";
        int num = 1;
        while (new File(zfileNm).exists()) {
            zfileNm = filePath + "_" + num++ + ".zip";
        }
        logger.debug("Zip File Path and Name : " + zfileNm);
        // Zip 파일을 만든다.
        File zfile = new File(zfileNm);
        // Zip 파일 객체를 출력 스트림에 넣는다.
        foutput = new FileOutputStream(zfile);
        // 집출력 스트림에 집파일을 넣는다.
        zoutput = new net.sf.jazzlib.ZipOutputStream((OutputStream)foutput);
        net.sf.jazzlib.ZipEntry zentry = null;
 
        try {
            for (int i=0; i < fileArray.length; i++) {
                // 압축할 파일 배열 중 하나를 꺼내서 입력 스트림에 넣는다.
                finput = new FileInputStream(fileArray[i]);
                // ze = new net.sf.jazzlib.ZipEntry ( inFile[i].getName());
                zentry = new net.sf.jazzlib.ZipEntry(fileArray[i].getName());
                logger.debug("Target File Name for Compression : "
                                    + fileArray[i].getName()
                                    + ", File Size : "
                                    + finput.available());
                zoutput.putNextEntry(zentry);
 
                /*
                 ****************************************************************
                 * 압축 레벨을 정하는것인데 9는 가장 높은 압축률을 나타냅니다.
                 * 그 대신 속도는 젤 느립니다. 디폴트는 8입니다.
                 *****************************************************************/
                zoutput.setLevel(COMPRESSION_LEVEL);
                cnt = 0;
                while ((cnt = finput.read(buffer)) != -1) {
                    zoutput.write(buffer, 0, cnt);
                }
                finput.close();
                zoutput.closeEntry();
            }
            zoutput.close();
            foutput.close();
        } catch (Exception e) {
            logger.fatal("Compression Error : " + e.toString());
            /*
             **********************************************
             * 압축이 실패했을 경우 압축 파일을 삭제한다.
             ***********************************************/
            logger.error(zfile.toString() + " : 압축이 실패하여 파일을 삭제합니다...");
            if (!zfile.delete()) {
                logger.error(zfile.toString() + " : 파일 삭제가 실패하여 다시 삭제합니다...");
                while(!zfile.delete()) {
                    logger.error(zfile.toString() + " : 삭제가 실패하여 다시 삭제합니다....");
                }
            }
            e.printStackTrace();
            throw new Exception(e);
        } finally {
            if (finput != null) {
                finput.close();
            }
            if (zoutput != null) {
                zoutput.close();
            }
            if (foutput != null) {
                foutput.close();
            }
        }
        long msec = System.currentTimeMillis() - beginTime;
        logger.debug("Check :: >> " + msec/1000 + "." + (msec % 1000) + " sec. elapsed...");
    }
}

0 0 1 1 0 0 0 0 0 0
List of Articles
번호 분류 제목 날짜 조회 수
공지 안내 🚨(뉴비필독) 전체공지 & 포인트안내 8 file 2024.11.04 25962
공지 System URL만 붙여넣으면 끝! 임베드 기능 2025.01.21 20461
378186 SNS📱 BABYMONSTER becomes Good Day’s brand ambassador! newfile 2025.06.10 1
378185 이슈 음원 발매 전 밴드 라이브로 선공개 한 키오프 신곡 newfile 2025.06.10 5
378184 치킨 vs 피자 1 new 2025.06.10 7
378183 잡담 요즘 전기자전거로 배달 안하나요 1 newfile 2025.06.10 28
378182 유머 본인 핏 자랑하다가 팩폭먹은 빠니보틀.jpg newfile 2025.06.10 30
378181 유머 본인 핏 자랑하다가 팩폭먹은 빠니보틀.jpg newfile 2025.06.10 27
378180 사진📷 250608 멤별 daily newfile 2025.06.10 50
378179 사진📷 팬싸인회 아태나 newfile 2025.06.10 50
378178 사진📷 빨간 태나♡ newfile 2025.06.10 56
378177 영상📹 보컬만 잘하는줄 알았더니 피프티피프티 아테나 250531 newfile 2025.06.10 46
Board Pagination Prev 1 2 3 4 5 ... 37819 Next
/ 37819