Piotr Gabryanczyk’s Blog

Java, Refactoring, AOP, Spring, DDD, TDD, etc.

  • Blogroll

    • I have joined Anti-IF Campaign

Archive for May, 2008

Mocking difficult objects like HttpServletRequest with CGLIB

Posted by Piotr Gabryanczyk on May 19, 2008

Why haven’t I seen this before?
http://www.sixlegs.com/blog/java/concrete-mock-objects.html

Advertisements

Posted in java | Tagged: , , , | 4 Comments »

Encoding in forms sent using POST method

Posted by Piotr Gabryanczyk on May 7, 2008

I struggled a lot with encoding in Tomcat before I found this post on Adam’s Warski blog.

Posted in java | Tagged: , , , | Leave a Comment »

How to UnZip archive in Java

Posted by Piotr Gabryanczyk on May 7, 2008

Why am I writing about it?

Because I could not find complete solution for unzipping archive in java.

Dependencies

You will need commons-io.jar from apache commons.

Random thoughts…

It is too small to release it as an open source library, and Apache Commons does not contain such a function, when I am writing it this post. Please feel free to copy/use/modify this code.

public class ZipUtils {
    Logger log;

    public ZipUtils(Logger log) {
        this.log = log;        
    }

    public void unzipArchive(File archive, File outputDir) {
        try {
            ZipFile zipfile = new ZipFile(archive);
            for (Enumeration e = zipfile.entries(); e.hasMoreElements(); ) {
                ZipEntry entry = (ZipEntry) e.nextElement();
                unzipEntry(zipfile, entry, outputDir);
            }
        } catch (Exception e) {
            log.error("Error while extracting file " + archive, e);
        }
    }

    private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {


        if (entry.isDirectory()) {
            createDir(new File(outputDir, entry.getName()));
            return;
        }
        
        File outputFile = new File(outputDir, entry.getName());
        if (!outputFile.getParentFile().exists()){
            createDir(outputFile.getParentFile());
        }

        log.debug("Extracting: " + entry);
        BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

        try {
            IOUtils.copy(inputStream, outputStream);
        } finally {
            outputStream.close();
            inputStream.close();
        }
    }

    private void createDir(File dir) {
        log.debug("Creating dir "+dir.getName());
        if(!dir.mkdirs()) throw new RuntimeException("Can not create dir "+dir);
    }
}

Posted in java | Tagged: | 7 Comments »