Java – use common IO to compress the directory into a zipfile

I am a beginner of Java programming. I am currently writing a program that must be able to compress and decompress Zip file application I can use the following code to extract the zipfile in Java using the built-in Java zip function and the Apache commons IO Library:

public static void decompressZipfile(String file,String outputDir) throws IOException {
    if (!new File(outputDir).exists()) {
        new File(outputDir).mkdirs();
    }
    ZipFile zipFile = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File entryDestination = new File(outputDir,entry.getName());
        if (entry.isDirectory()) {
            entryDestination.mkdirs();
        } else {
            InputStream in = zipFile.getInputStream(entry);
            OutputStream out = new FileOutputStream(entryDestination);
            IoUtils.copy(in,out);
            IoUtils.closeQuietly(in);
            IoUtils.closeQuietly(out);
        }
    }
}

In addition to the external libraries I used before, how will I create zip files from directories? (Java standard library and common IO)

Solution

The following method seems to successfully recursively compress the directory:

public static void compressZipfile(String sourceDir,String outputFile) throws IOException,FileNotFoundException {
    ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(outputFile));
    compressDirectoryToZipfile(sourceDir,sourceDir,zipFile);
    IoUtils.closeQuietly(zipFile);
}

private static void compressDirectoryToZipfile(String rootDir,String sourceDir,ZipOutputStream out) throws IOException,FileNotFoundException {
    for (File file : new File(sourceDir).listFiles()) {
        if (file.isDirectory()) {
            compressDirectoryToZipfile(rootDir,sourceDir + File.separator + file.getName(),out);
        } else {
            ZipEntry entry = new ZipEntry(sourceDir.replace(rootDir,"") + file.getName());
            out.putNextEntry(entry);

            FileInputStream in = new FileInputStream(sourceDir + file.getName());
            IoUtils.copy(in,out);
            IoUtils.closeQuietly(in);
        }
    }
}

As my compressed code snippet shows, I'm using ioutils Copy () to handle streaming data transmission

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>