Skip to content

Instantly share code, notes, and snippets.

@superzjn
Last active June 10, 2021 14:47
Show Gist options
  • Save superzjn/3416103fd672f22470ddc9a18b66ca70 to your computer and use it in GitHub Desktop.
Save superzjn/3416103fd672f22470ddc9a18b66ca70 to your computer and use it in GitHub Desktop.
[Unzip File] #FileIO
package com.superzjn;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnZip {
public File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
File destFile = new File(destinationDir, zipEntry.getName());
String destDirPath = destinationDir.getCanonicalPath();
String destFilePath = destFile.getCanonicalPath();
if (!destFilePath.startsWith(destDirPath + File.separator)) {
throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
}
return destFile;
}
public void unzipFile(String path) throws IOException {
byte[] buffer = new byte[2048];
// File destDir = new
// File("/home/superzjn/Documents/Java_Test/jsontest/target/classes/com/superzjn/unzipTest");
File destDir = new File("jsontest/target/classes/com/superzjn/unzipTest");
try (FileInputStream fis = new FileInputStream(path);
BufferedInputStream bis = new BufferedInputStream(fis);
ZipInputStream zipInputStream = new ZipInputStream(bis)) {
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null) {
File newFile = newFile(destDir, entry);
if (entry.isDirectory()) {
if (!newFile.isDirectory() && !newFile.mkdirs()) {
throw new IOException("Failed to create dir " + newFile);
}
} else {
// fix for Windows-created archives
File parent = newFile.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new IOException("Failed to create directory " + parent);
}
// write file content
try (FileOutputStream fos = new FileOutputStream(newFile)) {
int len;
while ((len = zipInputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
}
}
}
}
public static void main(String[] args) {
URL file = UnZip.class.getResource("package.zip");
UnZip unZip = new UnZip();
try {
unZip.unzipFile(file.getPath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment