From c15d382975807fcd2229e01291d21df84c28d170 Mon Sep 17 00:00:00 2001 From: terminator48 Date: Sat, 2 Apr 2016 17:00:00 +0600 Subject: [PATCH] FileSystem and Screen lib realization --- filesystem/src/main/java/UnzipUtility.java | 69 ++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100755 filesystem/src/main/java/UnzipUtility.java diff --git a/filesystem/src/main/java/UnzipUtility.java b/filesystem/src/main/java/UnzipUtility.java new file mode 100755 index 0000000..a3a37ec --- /dev/null +++ b/filesystem/src/main/java/UnzipUtility.java @@ -0,0 +1,69 @@ +import java.io.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +/** + * This utility extracts files and directories of a standard zip file to + * a destination directory. + * + * @author www.codejava.net + */ +public class UnzipUtility { + /** + * Size of the buffer to read/write data + */ + private static final int BUFFER_SIZE = 4096; + + /** + * Extracts a zip file specified by the zipFilePath to a directory specified by + * destDirectory (will be created if does not exists) + * + * @param zipFilePath path of the archive + * @param destDirectory where to extract to + * @throws IOException + */ + public void unzip(String zipFilePath, String destDirectory) throws IOException { + File destDir = new File(destDirectory); + if (!destDir.exists()) { + if (!destDir.mkdir()) + throw new IOException("Unable to create a root directory to unzip the archive"); + } + ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); + ZipEntry entry = zipIn.getNextEntry(); + // iterates over entries in the zip file + while (entry != null) { + String filePath = destDirectory + File.separator + entry.getName(); + if (!entry.isDirectory()) { + // if the entry is a file, extracts it + extractFile(zipIn, filePath); + } else { + // if the entry is a directory, make the directory + File dir = new File(filePath); + + if (!dir.mkdir()) { + throw new IOException("Unable to create a directory to unzip the directory"); + } + } + zipIn.closeEntry(); + entry = zipIn.getNextEntry(); + } + zipIn.close(); + } + + /** + * Extracts a zip entry (file entry) + * + * @param zipIn ZipInputStream + * @param filePath Where to extract to + * @throws IOException + */ + private void extractFile(ZipInputStream zipIn, String filePath) throws IOException { + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); + byte[] bytesIn = new byte[BUFFER_SIZE]; + int read; + while ((read = zipIn.read(bytesIn)) != -1) { + bos.write(bytesIn, 0, read); + } + bos.close(); + } +} \ No newline at end of file