Mercurial > dive4elements > gnv-client
view gnv-artifacts/src/main/java/de/intevation/gnv/utils/FileUtils.java @ 779:b1f5f2a8840f
Ordered imports. Removed needless imports. Removed empty headers.
gnv-artifacts/trunk@854 c6561f87-3c4e-4783-a992-168aeb5c3f6f
author | Sascha L. Teichmann <sascha.teichmann@intevation.de> |
---|---|
date | Mon, 29 Mar 2010 08:51:20 +0000 |
parents | eedad2ddad14 |
children | c4156275c1e1 |
line wrap: on
line source
package de.intevation.gnv.utils; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Stack; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @author Sascha L. Teichmann (sascha.teichmann@intevation.de) * @author Ingo Weinzierl (ingo.weinzierl@intevation.de) */ public final class FileUtils { private FileUtils() { } public final static void deleteContent(File dir) { if (dir == null || !dir.isDirectory()) { return; } File[] files = dir.listFiles(); if (files != null) { for (File file: files) { deleteRecursive(file); } } return; } public final static boolean deleteRecursive(File file) { if (file == null) { return false; } if (file.isDirectory()) { File [] files = file.listFiles(); if (files != null) { for (File sub: files) { if (!deleteRecursive(sub)) { return false; } } } } return file.delete(); } public static void createZipArchive( File file, OutputStream outputStream ) throws IOException { ZipOutputStream out = new ZipOutputStream(outputStream); if (file.isFile()) { copyFileToZip("", file, out); } else if (file.isDirectory()) { Stack<PrefixDir> stack = new Stack<PrefixDir>(); stack.push(new PrefixDir(file.getName() + "/", file)); while (!stack.isEmpty()) { PrefixDir pd = stack.pop(); ZipEntry dirEntry = new ZipEntry(pd.prefix); out.putNextEntry(dirEntry); out.closeEntry(); File [] files = pd.dir.listFiles(); if (files != null) { for (File sub: files) { if (sub.isDirectory()) { stack.push(new PrefixDir( pd.prefix + sub.getName() + "/", sub)); } else if (sub.isFile()) { copyFileToZip(pd.prefix, sub, out); } } } } } out.finish(); } private static final class PrefixDir { String prefix; File dir; public PrefixDir(String prefix, File dir) { this.prefix = prefix; this.dir = dir; } } // class PrefixDir private static void copyFileToZip( String prefix, File file, ZipOutputStream out ) throws IOException { String entryName = prefix + file.getName(); ZipEntry entry = new ZipEntry(entryName); out.putNextEntry(entry); InputStream in = null; try { in = new BufferedInputStream( new FileInputStream(file), 20*1024); byte [] buf = new byte[2048]; int r; while ((r = in.read(buf)) > 0) { out.write(buf, 0, r); } } finally { if (in != null) { try { in.close(); } catch (IOException ioe) {} } } out.closeEntry(); } } // vim:set ts=4 sw=4 si et sta sts=4 fenc=utf-8 :