본문 바로가기

IT/JAVA

JAVA 파일 압축 - P

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

 

public class Zip {

// 압축할 파일 디렉토리 경로

String path = null;

File f = null;

File[] fileList = null;

 

// 압축 파일을 저장할 디렉토리 경로 및 압축 파일 명

String zipFileName = null;

 

public static void main(String[] args) throws Exception {

Zip zip = new Zip();

zip.createZipFile("C:\\Users\\user\\Desktop\\aa\\",

"C:\\Users\\user\\Desktop", "test");

}

 

public void createZipFile(String dirPath, String zipPath, String zipName)

throws Exception {

// 압축할 파일 디렉토리 경로

path = dirPath;

f = new File(path);

fileList = f.listFiles();

 

// 압축 파일을 저장할 디렉토리 경로 및 압축 파일 명

zipFileName = zipPath + zipName;

net.sf.jazzlib.ZipOutputStream zos = null;

FileInputStream in = null;

byte[] buf = new byte[1024 * 16];

try {

zos = new net.sf.jazzlib.ZipOutputStream(new FileOutputStream(

zipFileName));

for (int i = 0; i < fileList.length; i++) {

File chkFile = fileList[i];

if (chkFile.isFile()) { // 파일만 압축

in = new FileInputStream(path + chkFile.getName());

zos.putNextEntry(new net.sf.jazzlib.ZipEntry(chkFile

.getName()));

int len;

while ((len = in.read(buf)) > 0) {

zos.write(buf, 0, len);

}

zos.closeEntry();

in.close();

 

// 압축 후 파일 삭제

// chkFile.delete();

} else {

// 하위의 디렉토리는 무시

System.out.println("더 이상의 하위 디렉토리는 압축하지 않습니다.");

}

}

zos.close();

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

} finally {

if (zos != null)

zos.close();

if (in != null)

in.close();

}

}

 

}