조회 수 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 0 1 0 0 0 1 3 1
List of Articles
번호 분류 제목 날짜 조회 수
공지 안내 🚨(뉴비필독) 전체공지 & 포인트안내 7 file 2024.11.04 25959
공지 System URL만 붙여넣으면 끝! 임베드 기능 2025.01.21 20461
377914 유머 미쳐돌아간다는 이민자 폭동사건 newfile 2025.06.09 110
377913 트럼프 LA 불법이민자 추방 취재하던 기자 newfile 2025.06.09 116
377912 생활용품 스텐 304싱크대 부수구망세트+숟가락불림통 19,900원 무배 newfile 2025.06.09 557
377911 노브랜드가 더맛잇는거같아 1 new 2025.06.09 114
377910 의류 기능성 반팔 티셔츠 6,500원 배송비 3,000원 newfile 2025.06.09 118
377909 생활용품 시온 국내생산 냉감 쿨매트 newfile 2025.06.09 1621
377908 유머 누적 조회수 4억 1천만이라는 웹툰 작가 newfile 2025.06.09 157
377907 내일 adhd 상담받으러간다 1 new 2025.06.09 131
377906 논란 스트리머 복귀어케생각해? 3 new 2025.06.09 138
377905 진짜 지하철이 무서워... 1 new 2025.06.09 145
Board Pagination Prev 1 2 3 4 5 ... 37792 Next
/ 37792