forked from hmkcode/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnzip.java
More file actions
71 lines (51 loc) · 1.7 KB
/
Unzip.java
File metadata and controls
71 lines (51 loc) · 1.7 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
package com.hmkcode;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Unzip {
public static void unzip(String zipFile,String outputPath){
if(outputPath == null)
outputPath = "";
else
outputPath+=File.separator;
// 1.0 Create output directory
File outputDirectory = new File(outputPath);
if(outputDirectory.exists())
outputDirectory.delete();
outputDirectory.mkdir();
// 2.0 Unzip (create folders & copy files)
try {
// 2.1 Get zip input stream
ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry entry = null;
int len;
byte[] buffer = new byte[1024];
// 2.2 Go over each entry "file/folder" in zip file
while((entry = zip.getNextEntry()) != null){
if(!entry.isDirectory()){
System.out.println("-"+entry.getName());
// create a new file
File file = new File(outputPath +entry.getName());
// create file parent directory if does not exist
if(!new File(file.getParent()).exists())
new File(file.getParent()).mkdirs();
// get new file output stream
FileOutputStream fos = new FileOutputStream(file);
// copy bytes
while ((len = zip.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
}
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}