java zip file use Apache Compress
class="java" name="code">
private void zip(File file) throws IOException {
zipFile = new File(file.getParent(), file.getName()+".zip");
FileOutputStream fOut = null;
BufferedOutputStream bOut = null;
ZipArchiveOutputStream tOut = null;
try {
fOut = new FileOutputStream(zipFile);
bOut = new BufferedOutputStream(fOut);
tOut = new ZipArchiveOutputStream(bOut);
addFileToZip(tOut, file, "");
} finally {
if(tOut!=null){
tOut.finish();
}
tOut.close();
bOut.close();
fOut.close();
}
}
private void addFileToZip(ZipArchiveOutputStream zOut, File file, String base) throws IOException {
String entryName = base + file.getName();
ZipArchiveEntry zipEntry = new ZipArchiveEntry(file, entryName);
zOut.putArchiveEntry(zipEntry);
if (file.isFile()) {
FileInputStream fInputStream = null;
try {
fInputStream = new FileInputStream(file);
IOUtils.copy(fInputStream, zOut);
zOut.closeArchiveEntry();
} finally {
IOUtils.closeQuietly(fInputStream);
}
} else {
zOut.closeArchiveEntry();
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
addFileToZip(zOut, child, entryName + "/");
}
}
}
}
java upzip file
private void unZipFile(File fSourceZip) throws ZipException, IOException {
long fileSize=0;
String zipPath = fSourceZip.getParentFile().getAbsolutePath();
File temp = new File(zipPath);
temp.mkdir();
temp.setExecutable(true);
temp.setReadable(true);
temp.setWritable(true);
ZipFile zipFile = new ZipFile(fSourceZip);
Enumeration e = zipFile.entries();
boolean createFolder = true;
while (e.hasMoreElements()) {
ZipEntry entry = (ZipEntry) e.nextElement();
File destinationFilePath = new File(zipPath, entry.getName());
destinationFilePath.setExecutable(true);
destinationFilePath.setReadable(true);
destinationFilePath.setWritable(true);
if (createFolder) {
destinationFilePath.getParentFile().mkdirs();
}
if (entry.isDirectory()) {
continue;
} else {
createFolder = true;
BufferedInputStream bis = new BufferedInputStream(
zipFile.getInputStream(entry));
int b;
byte buffer[] = new byte[1024];
FileOutputStream fos = new FileOutputStream(
destinationFilePath);
BufferedOutputStream bos = new BufferedOutputStream(fos,
1024);
while ((b = bis.read(buffer, 0, 1024)) != -1) {
bos.write(buffer, 0, b);
}
bos.flush();
bos.close();
bis.close();
}
fileSize = fileSize + destinationFilePath.length();
}
zipFile.close();
fSourceZip.delete();
}