Jun 052011
 
package sactosoft.filedecompressor;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class FileDecompressor {
    static final int BUFFER = 2048;

    public static final boolean UseFolderNames = true;

    public static void decompress(String inputFile, String outputPath, boolean useFolderNames) throws Exception {
        inputFile = inputFile.trim().replace('\\', '/');
        outputPath = getOutputPath(inputFile, outputPath);

        BufferedInputStream is = null;

        if (inputFile.toLowerCase().endsWith("gz")) {
            GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(inputFile));
            is = new BufferedInputStream(gzis);
            String outputFile = outputPath + "/"
                    + inputFile.substring(inputFile.lastIndexOf('/') + 1, inputFile.length() - 3);
            createOutFile(is, outputFile);
        } else {
            ZipEntry entry;
            ZipFile zipfile = new ZipFile(inputFile);
            Enumeration e = zipfile.entries();

            while (e.hasMoreElements()) {
                entry = (ZipEntry) e.nextElement();
                String outputFileName;
                if (useFolderNames) {
                    outputFileName = entry.getName();
                } else {
                    outputFileName = entry.getName().replace('\\', '/');
                    if (outputFileName.contains("/")) {
                        outputFileName = outputFileName.substring(outputFileName.lastIndexOf('/') + 1);
                    }
                }
                is = new BufferedInputStream(zipfile.getInputStream(entry));
                createOutFile(is, outputFileName);
            }
        }

    }

    // -----
    private static String getOutputPath(String inputFile, String outputPath) {
        if (outputPath == null) {
            // inputFile = inputFile.trim().replace('\\', '/');
            String inputPath = inputFile.substring(0, inputFile.lastIndexOf("/"));
            outputPath = inputPath;
        } else {
            outputPath = outputPath.trim().replace('\\', '/');
            if (outputPath.endsWith("/")) {
                outputPath = outputPath.substring(0, outputPath.length() - 1);
            }
        }
        return outputPath;
    }

    private static void createOutFile(BufferedInputStream is, String outputFile) throws Exception {
        BufferedOutputStream dest = null;
        int count;
        byte data[] = new byte[BUFFER];
        FileOutputStream fos = new FileOutputStream(outputFile);
        dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = is.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
        is.close();
    }
}