Mercurial > dive4elements > framework
diff artifacts-common/src/main/java/de/intevation/artifacts/common/utils/FileTools.java @ 383:b076c9e9fdfd
Added method to extract zip archives to a specified directory.
artifacts/trunk@4293 c6561f87-3c4e-4783-a992-168aeb5c3f6f
author | Raimund Renkert <raimund.renkert@intevation.de> |
---|---|
date | Wed, 25 Apr 2012 07:47:56 +0000 |
parents | c489256a188b |
children | c40729bfe06d |
line wrap: on
line diff
--- a/artifacts-common/src/main/java/de/intevation/artifacts/common/utils/FileTools.java Thu Apr 19 18:20:55 2012 +0000 +++ b/artifacts-common/src/main/java/de/intevation/artifacts/common/utils/FileTools.java Wed Apr 25 07:47:56 2012 +0000 @@ -14,6 +14,7 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; +import java.io.BufferedOutputStream; import java.nio.channels.FileChannel; import java.util.Deque; @@ -22,6 +23,8 @@ import java.util.Set; import java.util.HashSet; import java.util.ArrayList; +import java.util.Enumeration; +import java.util.zip.ZipFile; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @@ -347,6 +350,57 @@ out.finish(); } + + public static void extractArchive(File archive, File destDir) + throws IOException { + if (!destDir.exists()) { + destDir.mkdir(); + } + + ZipFile zipFile = new ZipFile(archive); + Enumeration entries = zipFile.entries(); + + byte[] buffer = new byte[16384]; + int len; + while (entries.hasMoreElements()) { + ZipEntry entry = (ZipEntry) entries.nextElement(); + + String entryFileName = entry.getName(); + + File dir = dir = buildDirectoryHierarchyFor(entryFileName, destDir); + if (!dir.exists()) { + dir.mkdirs(); + } + + if (!entry.isDirectory()) { + BufferedOutputStream bos = new BufferedOutputStream( + new FileOutputStream(new File(destDir, entryFileName))); + + BufferedInputStream bis = new BufferedInputStream(zipFile + .getInputStream(entry)); + + while ((len = bis.read(buffer)) > 0) { + bos.write(buffer, 0, len); + } + + bos.flush(); + bos.close(); + bis.close(); + } + } + zipFile.close(); + } + + private static File buildDirectoryHierarchyFor( + String entryName, + File destDir) + { + int lastIndex = entryName.lastIndexOf('/'); + String entryFileName = entryName.substring(lastIndex + 1); + String internalPathToEntry = entryName.substring(0, lastIndex + 1); + return new File(destDir, internalPathToEntry); + } + /** * A class representing a directory with a prefix. */