개발

자바로 Zip 파일 압축 및 풀기

에드몽단테스 2007. 5. 7. 23:59
import java.util.zip.*;
import java.util.Enumeration;

// 압축하기
File dir = new File("c:\\temp");
String[] fnames = dir.list();
byte[] bytes = new byte[4096];
       
String targetName = "c:\\zipfiletest.zip";
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(targetName));
       
for(int i=0; i
{
    FileInputStream fis = new FileInputStream("c:\\temp\\"+fnames[i]);
    zos.putNextEntry(new ZipEntry("c:\\temp\\"+fnames[i]));
           
   int len = 0;
    while((len = fis.read(bytes)) > 0)
    {
        zos.write(bytes, 0, len);
    }
    zos.closeEntry();
    fis.close();
}
zos.close();


// 압축해제하기
File tmp_dir = new File("tmp");    // 압축을 해제할 임시 파일
if(!tmp_dir.exists())
    tmp_dir.mkdirs();

try {
    ZipFile zipFile = new ZipFile("random.zip");
    Enumeration enu = (Enumeration) zipFile.entries();
    byte[] bytes = new byte[4096];
    int index = -1;
    while(enu.hasMoreElements()) {
        ZipEntry entry = enu.nextElement();
        String name  = entry.getName();

        // 파일이 디렉토리 안에 포함되어 있는 경우 디렉토리를 별도로 만들어주어야 한다.
        index = name.lastIndexOf("/");
        if(index != -1){
            File mFile = new File(tmp_dir, name.substring(0, index));
            if(!mFile.exists())
                mFile.mkdirs();
        }
       
        InputStream in = zipFile.getInputStream(entry);
        FileOutputStream fos = new FileOutputStream(new File(tmp_dir, name));
        int red = -1;
        while(true) {
            red = in.read(bytes);
            if(red < 0)
                break;
            fos.write(bytes, 0, red);
        }
        fos.flush();
        fos.close();
    }
    zipFile.close();
} catch (IOException e) {
    e.printStackTrace();
}

반응형