Unzipping in Java and FileUtil.copy
- by Geertjan
Via NetBeans File Systems API, which provides FileUtil.copy below, which means a dependency on NetBeans Utilities API:
private void unzipEpubFile(String folder, File file) throws IOException {
final AtomicBoolean canceled = new AtomicBoolean();
//define and start progress bar here...
// ProgressHandle handle =
// ProgressHandleFactory.createHandle(
// Bundle.MSG_unpacking(zip.getName()),
// new Cancellable() {
// @Override
// public boolean cancel() {
// return canceled.compareAndSet(false, true);
// }
// });
//then unzip 'file' into 'root":
try {
List folders = new ArrayList<>();
try (InputStream is = new FileInputStream(file)) {
ZipInputStream zis = new ZipInputStream(is);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (canceled.get()) {
return;
}
String n = entry.getName();
File f = new File(folder, n);
if (n.endsWith("/")) {
if (!f.isDirectory()) {
if (!f.mkdirs()) {
throw new IOException("could not make " + f);
}
if (entry.getTime() > 0) {
if (!f.setLastModified(entry.getTime())) {
// oh well
}
}
}
folders.add(f);
} else {
//handle.progress(Bundle.MSG_creating(n));
File p = f.getParentFile();
if (!p.isDirectory() && !p.mkdirs()) {
throw new IOException("could not make " + p);
}
try (OutputStream os = new FileOutputStream(f)) {
FileUtil.copy(zis, os);
}
if (entry.getTime() > 0) {
if (!f.setLastModified(entry.getTime())) {
// oh well
}
}
}
}
}
//handle.switchToDeterminate(folders.size());
if (canceled.get()) {
}
} finally {
//stop progress bar
}
}
Mostly from NetBeans IDE sources for working with projects and ZIP files.