# HG changeset patch # User Raimund Renkert # Date 1335340076 0 # Node ID b076c9e9fdfdc7cedb0af47cd70fbff51ca61141 # Parent a94bc2491b418abaf7815037d483e5d830126aa5 Added method to extract zip archives to a specified directory. artifacts/trunk@4293 c6561f87-3c4e-4783-a992-168aeb5c3f6f diff -r a94bc2491b41 -r b076c9e9fdfd ChangeLog --- a/ChangeLog Thu Apr 19 18:20:55 2012 +0000 +++ b/ChangeLog Wed Apr 25 07:47:56 2012 +0000 @@ -1,3 +1,8 @@ +2012-04-25 Raimund Renkert + + * artifacts-common/src/main/java/de/intevation/artifacts/common/utils/FileTools.java: + Added method to extract zip archives to a specified directory. + 2012-04-19 Sascha L. Teichmann * artifacts-common/src/main/java/de/intevation/artifacts/common/utils/XSLTransformer.java: diff -r a94bc2491b41 -r b076c9e9fdfd artifacts-common/src/main/java/de/intevation/artifacts/common/utils/FileTools.java --- 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. */