-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaZipProgram
More file actions
90 lines (75 loc) · 2.34 KB
/
JavaZipProgram
File metadata and controls
90 lines (75 loc) · 2.34 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
package Questions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFiles {
List<String> filesListInDir = new ArrayList<String>();
public static void main(String[] args) {
File file = new File("C:\\Users\\suhas\\Desktop\\urls.txt");
String zipFileName = "C:\\Users\\suhas\\Desktop\\urls.zip";
File dir = new File("C:\\Users\\A734677\\Desktop\\Pics");
String zipDirName = "C:\\Users\\A734677\\Desktop\\Pics.zip";
zipSingleFile(file, zipFileName);
ZipFiles zipFiles = new ZipFiles();
zipFiles.zipDirectory(dir, zipDirName);
}
private void zipDirectory(File dir, String zipDirName) {
try {
populateFilesList(dir);
FileOutputStream fos = new FileOutputStream(zipDirName);
ZipOutputStream zos = new ZipOutputStream(fos);
for (String filePath : filesListInDir) {
System.out.println("Zipping " + filePath);
ZipEntry ze = new ZipEntry(filePath.substring(dir.getAbsolutePath().length() + 1, filePath.length()));
zos.putNextEntry(ze);
FileInputStream fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
fis.close();
}
zos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void populateFilesList(File dir) throws IOException {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isFile())
filesListInDir.add(file.getAbsolutePath());
else
populateFilesList(file);
}
}
private static void zipSingleFile(File file, String zipFileName) {
try {
FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry(file.getName());
zos.putNextEntry(ze);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
zos.close();
fis.close();
fos.close();
System.out.println(file.getCanonicalPath() + " is zipped to " + zipFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}