118 lines
2.6 KiB
Java
118 lines
2.6 KiB
Java
package com.flaremicro.util;
|
|
|
|
import java.io.BufferedInputStream;
|
|
import java.io.File;
|
|
import java.io.FileInputStream;
|
|
import java.io.FileOutputStream;
|
|
import java.io.IOException;
|
|
import java.util.Enumeration;
|
|
import java.util.zip.ZipEntry;
|
|
import java.util.zip.ZipException;
|
|
import java.util.zip.ZipFile;
|
|
import java.util.zip.ZipOutputStream;
|
|
|
|
public class ZipUtils {
|
|
|
|
public static void zipDirectory(File sourceDir, File zipFile) throws IOException {
|
|
FileOutputStream fos = new FileOutputStream(zipFile);
|
|
ZipOutputStream zos = new ZipOutputStream(fos);
|
|
try
|
|
{
|
|
zipFilesRecursively(sourceDir, sourceDir, zos);
|
|
}
|
|
finally
|
|
{
|
|
zos.close();
|
|
}
|
|
}
|
|
|
|
private static void zipFilesRecursively(File rootDir, File source, ZipOutputStream zos) throws IOException {
|
|
if (source.isDirectory())
|
|
{
|
|
File[] files = source.listFiles();
|
|
if (files != null)
|
|
{
|
|
for (File file : files)
|
|
{
|
|
zipFilesRecursively(rootDir, file, zos);
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
FileInputStream fis = null;
|
|
try
|
|
{
|
|
fis = new FileInputStream(source);
|
|
// Create the relative path for the entry
|
|
String zipEntryName = source.getAbsolutePath().substring(rootDir.getAbsolutePath().length() + 1).replace("\\", "/");
|
|
ZipEntry zipEntry = new ZipEntry(zipEntryName);
|
|
zos.putNextEntry(zipEntry);
|
|
|
|
byte[] buffer = new byte[4096];
|
|
int bytesRead;
|
|
while ((bytesRead = fis.read(buffer)) != -1)
|
|
{
|
|
zos.write(buffer, 0, bytesRead);
|
|
}
|
|
zos.closeEntry();
|
|
}
|
|
finally
|
|
{
|
|
Util.cleanClose(fis);
|
|
}
|
|
}
|
|
}
|
|
|
|
public static boolean unzipDirectory(File zipFile, File destination) {
|
|
ZipFile zip = null;
|
|
try
|
|
{
|
|
zip = new ZipFile(zipFile);
|
|
Enumeration<? extends ZipEntry> zipEntries = zip.entries();
|
|
while (zipEntries.hasMoreElements())
|
|
{
|
|
ZipEntry zipEntry = zipEntries.nextElement();
|
|
File newFile = new File(destination, zipEntry.getName());
|
|
|
|
//create sub directories
|
|
newFile.getParentFile().mkdirs();
|
|
|
|
if (!zipEntry.isDirectory())
|
|
{
|
|
FileOutputStream outputStream = null;
|
|
BufferedInputStream inputStream = null;
|
|
try
|
|
{
|
|
outputStream = new FileOutputStream(newFile);
|
|
inputStream = new BufferedInputStream(zip.getInputStream(zipEntry));
|
|
while (inputStream.available() > 0)
|
|
{
|
|
outputStream.write(inputStream.read());
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
Util.cleanClose(outputStream);
|
|
Util.cleanClose(inputStream);
|
|
}
|
|
}
|
|
|
|
}
|
|
return true;
|
|
}
|
|
catch (ZipException e)
|
|
{
|
|
e.printStackTrace();
|
|
}
|
|
catch (IOException e)
|
|
{
|
|
e.printStackTrace();
|
|
}
|
|
finally
|
|
{
|
|
Util.cleanClose(zip);
|
|
}
|
|
return false;
|
|
}
|
|
} |