자바압축파일생성

자바 압축파일 생성 방법

이번에는 자바코딩으로 압축파일을 생성하는 방법을 포스팅 해보겠습니다.
서버에서 파일을 다운또는 생성하여 압축파일을 생성하는 방법입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
* @param inputFolder = 압축할 폴더의 위치
* @param filePath = 압축파일을 생성시킬 위치
* @param zipName = 압축파일의 이름
* 이렇게 인자값으로 받지 않고 메소드안에서 설정해도 무방합니다.
*/
public static void zip(String inputFolder, String filePath, String zipName)
throws Exception {
//압축파일을 저장할 파일을 선언한다.
FileOutputStream fileOutputStream = null;
File file = new File(filePath+File.separator+"zipName");
fileOutputStream = new FileOutputStream(file);
//ZipOutputStream 선언
ZipOutputStream zipOutputStream =
new ZipOutputStream(fileOutputStream);
//압축할 대상이 있는 폴더를 파일로 선언한다.
File inputFile = new File(inputFolder);
//압축을 할 대상이 file이면 zipFile 메소드를,
//폴더이면 zipFolder 메소드를 호출한다.
if(inputFile.isFile()) {
zipFile(inputFile)
} else if(inputFile.isDirectory()) {
zipFolder(zipOutputStream,inputFile,"");
}
zipOutputStream.close();
fileOutputStream.close();
}
public static void zipFolder(ZipOutputStream zipOutputStream, File inputFile,
String parentName) throws Exception {
String myName = parentName+inputFolder.getName()+File.separator;
//ZipEntry를 생성 후 zip 메소드에서 인자값으로 받은 파일의 구성 정보를 생성한다.
ZipEntry folderZipEntry = new ZipEntry(myName);
zipOutputStream.putNextEntry(folderZipEntry);
//zip 메소드에서 인자값으로 전달받은 파일의 구성파일들을 list형식으로 저장한다.
File[] contents = inputFile.listFiles();
//inputFolder의 구성파일이 파일이면 zipFile 메소드를 호출하고,
//폴더일 경우 현재 zipFolder 메소드를 재귀호출
for(File file : contents) {
if(file.isFile()) {
zipFile(file,myName,zipOutputStream);
} else if(file.isDirectory()) {
zipFolder(zipOutputStream,file,myName);
}
zipOutputStream.closeEntry();
}
}
public static void zipFile(File inputFile, String parentName,
ZipOutputStream zipOutputStream) throws Exception {
//ZipEntry생성 후 zip 메소드에서 인자값으로 전달받은 파일의 구성 정보를 생성한다.
ZipEntry zipEntry = new ZipEntry(parentName+inputFile.getName());
zipOutputStream.putNextEntry(zipEntry);
FileInputStream fileInputStream = new FileInputStream(inputFile);
byte[] buf = new byte[4096];
int byteRead;
//압축대상 파일을 설정된 사이즈만큼 읽어들인다.
//buf의 size는 원하는대로 설정가능하다.
while((byteRead = fileInputStream.read(buf))>0) {
zipOutputStream.write(buf,0,bytesRead);
}
zipOutputStream.closeEntry();
fileInputStream.close();
}

이렇게 Folder에서 접근하여 File만 찾아 압축하는 형식으로 압축을 한다.
이렇게 자바에서 압축을 할때 주의할점은 인코딩 문제로 압축파일이름이 한글이 포함되어있으면 불가능하다.
숫자,영문으로만 파일이름들을 설정한다.

Share