Java Path Extract nio extract(Path archive, Path targetDirectory)

Here you can find the source of extract(Path archive, Path targetDirectory)

Description

Extracts a ZIP archive into the target directory

License

Open Source License

Parameter

Parameter Description
archive Path to the archive to extract
targetDirectory Directory to which the files will be extracted

Exception

Parameter Description
Exception an exception

Declaration

public static synchronized void extract(Path archive, Path targetDirectory) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;

import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Main {
    protected static final int bufferSize = 1024;

    /**// w w w  .j  a  va  2 s  .  c  o m
     * Extracts a ZIP archive into the target directory
     * 
     * @param archive            Path to the archive to extract
     * @param targetDirectory      Directory to which the files will be extracted
     * @throws Exception
     */
    public static synchronized void extract(Path archive, Path targetDirectory) throws Exception {
        System.out.println("Unzipping " + archive.getFileName().toString() + "...");
        byte[] buffer = new byte[bufferSize];

        // extracts the source code archive to the target directory
        try (ZipInputStream zin = new ZipInputStream(new FileInputStream(archive.toFile()))) {
            ZipEntry ze;
            while ((ze = zin.getNextEntry()) != null) {
                Path extractedFile = targetDirectory.resolve(ze.getName());
                try (FileOutputStream fout = new FileOutputStream(extractedFile.toFile())) {

                    int len;
                    while ((len = zin.read(buffer)) > 0) {
                        fout.write(buffer, 0, len);
                    }

                    zin.closeEntry();
                } catch (IOException ioe_inner) {
                    throw new Exception("Error while extracting a file from the archive: " + extractedFile);
                }
            }
        } catch (IOException ioe_outter) {
            throw new Exception("Error while extracting " + archive);
        }
        System.out.println("Unzipping " + archive.getFileName().toString() + " done.");
    }
}

Related

  1. extractClassName(Path path)
  2. extractCurrentPath()
  3. extractFile(ZipInputStream zipIn, Path filePath)
  4. extractLanguageRelativePath(final Path absolutePath)