Created
October 26, 2012 10:22
-
-
Save monzou/3958037 to your computer and use it in GitHub Desktop.
SimpleZipFileCompressor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sandbox; | |
import java.io.BufferedInputStream; | |
import java.io.BufferedOutputStream; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.util.zip.ZipEntry; | |
import java.util.zip.ZipInputStream; | |
import java.util.zip.ZipOutputStream; | |
import org.apache.commons.io.IOUtils; | |
/** | |
* SimpleZipCompressor | |
* | |
* @author monzou | |
*/ | |
class SimpleZipCompressor { | |
private SimpleZipCompressor() { | |
} | |
static void zip(File source, File dest) throws IOException { | |
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(dest)); | |
ZipOutputStream zos = new ZipOutputStream(os); | |
ZipEntry ze = new ZipEntry(source.getName()); | |
InputStream is = null; | |
try { | |
zos.putNextEntry(ze); | |
is = new BufferedInputStream(new FileInputStream(source)); | |
byte[] buf = new byte[1024]; | |
int len; | |
while ((len = is.read(buf)) > 0) { | |
zos.write(buf, 0, len); | |
} | |
} finally { | |
if (is != null) { | |
IOUtils.closeQuietly(is); | |
} | |
try { | |
zos.closeEntry(); | |
} finally { | |
IOUtils.closeQuietly(zos); | |
} | |
} | |
source.delete(); | |
} | |
static void unzip(File source) throws IOException { | |
ZipInputStream zis = new ZipInputStream(new FileInputStream(source)); | |
ZipEntry entry; | |
try { | |
while ((entry = zis.getNextEntry()) != null) { | |
File dest = new File(source.getParent(), entry.getName()); | |
BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(dest)); | |
try { | |
int size; | |
byte[] buf = new byte[1024]; | |
while ((size = zis.read(buf, 0, buf.length)) != -1) { | |
os.write(buf, 0, size); | |
} | |
os.flush(); | |
} finally { | |
IOUtils.closeQuietly(os); | |
} | |
} | |
} finally { | |
try { | |
zis.closeEntry(); | |
} finally { | |
IOUtils.closeQuietly(zis); | |
} | |
} | |
source.delete(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment