개발 & 데이터베이스/JAVA

자바 해당 경로에 있는 모든 파일 압축하는 방법

K.두부 2022. 10. 11. 22:22
반응형

안녕하세요. 두부입니다.

자바에서 제공하는 기능으로 파일 압축을 해보겠습니다. 

이클립스 외에 필요한 것은 없고 아래의 코드는 아주 간단한 파일 압축 코드입니다.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Main {
public static void main(String[] args) throws IOException {
String filePath = "C:/test/a"; // 압축할 파일이 있는 경로
File file = new File(filePath);
File[] listFiles = file.listFiles();
FileOutputStream fos = null;
FileInputStream fis = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(filePath + "/output.zip"); // 압축파일 명
zos = new ZipOutputStream(fos);
for (File fileZip : listFiles) {
fis = new FileInputStream(fileZip);
ZipEntry zipEntry = new ZipEntry(fileZip.getName());
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int len;
while((len = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, len);
}
fis.close();
zos.closeEntry();
}
zos.close();
fos.close();
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
if (fos != null) fos.close();
if (fis != null) fis.close();
if (zos != null) zos.close();
}
}
}

위의 코드를 실행해보면 해당 경로에 zip파일이 생성되며 모든 파일을 압축한 것을 볼 수 있습니다.

 

 

반응형