본문 바로가기
IT/Java

폴더 zip로 압축

by 봉즙 2020. 8. 5.
import java.io.*;
import java.net.URI;
import java.util.Deque;
import java.util.LinkedList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Zip {
    public static void main(String[] args) throws IOException {


        zip("C://workspace/jsSpeedTest", "C://workspace/file.zip");
    }


    public static void zip(String directoryStr, String zipFileStr) throws IOException {
         //압축할 폴더
        File dir = new File(directoryStr);
        
        //zipFile 경로
        File zipFile = new File(zipFileStr);
        
        URI base = directory.toURI();
        Deque<File> deque = new LinkedList<File>();
        deque.push(directory);
        OutputStream out = new FileOutputStream(zipFile);
        Closeable res = out;
        try {
            ZipOutputStream zout = new ZipOutputStream(out);
            res = zout;
            while (!deque.isEmpty()) {
                directory = deque.pop();
                for (File kid : directory.listFiles()) {
                    String name = base.relativize(kid.toURI()).getPath();
                    //폴더면 경로 하나 더 들어가서 압축
                    if (kid.isDirectory()) {
                        deque.push(kid);
                        name = name.endsWith("/") ? name : name + "/";
                        zout.putNextEntry(new ZipEntry(name));
                    } else {
                        //파일이면 그냥 압축
                        zout.putNextEntry(new ZipEntry(name));

                        //private static void copy(File file, OutputStream out) 실행
                        copy(kid, zout);
                        zout.closeEntry();
                    }
                }
            }
        } finally {
            res.close();
        }
    }

    private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        while (true) {
            int readCount = in.read(buffer);
            if (readCount < 0) {
                break;
            }
            out.write(buffer, 0, readCount);
        }
    }

    private static void copy(File file, OutputStream out) throws IOException {
        InputStream in = new FileInputStream(file);
        try {
            //copy(InputStream in, OutputStream out) 실행
            copy(in, out);
        } finally {
            in.close();
        }
    }
}

'IT > Java' 카테고리의 다른 글

2021-10-13-SingleTon  (0) 2023.02.27
2021-01-13-replaceAll-No-group-2-에러  (0) 2023.02.27
Arrays.asList()  (0) 2020.07.28
Thread Safe  (0) 2020.07.08
Field Injection | Contructor Injection  (0) 2020.07.07

댓글