Example usage for org.apache.commons.compress.archivers.sevenz SevenZFile close

List of usage examples for org.apache.commons.compress.archivers.sevenz SevenZFile close

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.sevenz SevenZFile close.

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes the archive.

Usage

From source file:at.treedb.util.SevenZip.java

/**
 * Extracts some data (files and directories) from the archive without
 * extracting the whole archive.//from  w ww.  j a  v a2 s  .c om
 * 
 * @param archive
 *            7-zip archive
 * @param fileList
 *            file extraction list, a path with an ending '/' denotes a
 *            directory
 * @return file list as a map file name/file data
 * @throws IOException
 */
public static HashMap<String, byte[]> exctact(File archive, String... fileList) throws IOException {
    HashSet<String> fileSet = new HashSet<String>();
    ArrayList<String> dirList = new ArrayList<String>();
    for (String f : fileList) {
        if (!f.endsWith("/")) {
            fileSet.add(f);
        } else {
            dirList.add(f);
        }
    }
    HashMap<String, byte[]> resultMap = new HashMap<String, byte[]>();
    SevenZFile sevenZFile = new SevenZFile(archive);
    do {
        SevenZArchiveEntry entry = sevenZFile.getNextEntry();
        if (entry == null) {
            break;
        }
        // convert window path to unix style
        String name = entry.getName().replace('\\', '/');
        if (!entry.isDirectory()) {
            boolean storeFile = false;
            if (fileSet.contains(name)) {
                storeFile = true;
            } else {
                // search directories
                for (String s : dirList) {
                    if (name.startsWith(s)) {
                        storeFile = true;
                        break;
                    }
                }
            }
            // store the file
            if (storeFile) {
                int size = (int) entry.getSize();
                byte[] data = new byte[size];
                sevenZFile.read(data, 0, size);
                resultMap.put(name, data);
                // in this case we can finish the extraction loop
                if (dirList.isEmpty() && resultMap.size() == fileSet.size()) {
                    break;
                }
            }
        }
    } while (true);
    sevenZFile.close();
    return resultMap;
}

From source file:com.espringtran.compressor4j.processor.SevenZipProcessor.java

/**
 * Read from compressed file/*w w  w  .j a  va  2 s . com*/
 * 
 * @param srcPath
 *            path of compressed file
 * @param fileCompressor
 *            FileCompressor object
 * @throws Exception
 */
@Override
public void read(String srcPath, FileCompressor fileCompressor) throws Exception {
    long t1 = System.currentTimeMillis();
    byte[] data = FileUtil.convertFileToByte(srcPath);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    SevenZFile sevenZFile = new SevenZFile(new File(srcPath));
    try {
        byte[] buffer = new byte[1024];
        int readByte;
        SevenZArchiveEntry entry = sevenZFile.getNextEntry();
        while (entry != null && entry.getSize() > 0) {
            long t2 = System.currentTimeMillis();
            baos = new ByteArrayOutputStream();
            readByte = sevenZFile.read(buffer);
            while (readByte != -1) {
                baos.write(buffer, 0, readByte);
                readByte = sevenZFile.read(buffer);
            }
            BinaryFile binaryFile = new BinaryFile(entry.getName(), baos.toByteArray());
            fileCompressor.addBinaryFile(binaryFile);
            LogUtil.createAddFileLog(fileCompressor, binaryFile, t2, System.currentTimeMillis());
            entry = sevenZFile.getNextEntry();
        }
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on get compressor file", e);
    } finally {
        sevenZFile.close();
        baos.close();
    }
    LogUtil.createReadLog(fileCompressor, srcPath, data.length, t1, System.currentTimeMillis());
}

From source file:inventory.pl.services.BackupService.java

public void restore(String source, String outputFolder) {
    byte[] buffer = new byte[1024];

    try {/*  w  ww . jav  a 2s  . c  o  m*/

        //create output directory is not exists
        File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }

        //get the zip file content
        SevenZFile sevenZFile = new SevenZFile(new File(source));
        //get the zipped file list entry
        SevenZArchiveEntry ze = sevenZFile.getNextEntry();

        while (ze != null) {

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);

            System.out.println("file unzip : " + newFile.getAbsoluteFile());

            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);

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

            fos.close();
            ze = sevenZFile.getNextEntry();
        }

        sevenZFile.close();

        System.out.println("Done");

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:org.apache.ant.compress.resources.SevenZResource.java

/**
 * Return an InputStream for reading the contents of this Resource.
 * @return an InputStream object./*w  ww. j a  va  2s . c o m*/
 * @throws IOException if the sevenz file cannot be opened,
 *         or the entry cannot be read.
 */
public InputStream getInputStream() throws IOException {
    if (isReference()) {
        return ((Resource) getCheckedRef()).getInputStream();
    }
    File f = getSevenZFile();
    if (f == null) {
        return super.getInputStream();
    }

    final SevenZFile z = new SevenZFile(f);
    SevenZArchiveEntry ze = z.getNextEntry();
    while (ze != null) {
        if (ze.getName().equals(getName())) {
            return new InputStream() {
                public int read() throws IOException {
                    return z.read();
                }

                public int read(byte[] b) throws IOException {
                    return z.read(b);
                }

                public void close() throws IOException {
                    z.close();
                }

                protected void finalize() throws Throwable {
                    try {
                        close();
                    } finally {
                        super.finalize();
                    }
                }
            };
        }
        ze = z.getNextEntry();
    }
    z.close();
    throw new BuildException("no entry " + getName() + " in " + getArchive());
}

From source file:org.apache.ant.compress.resources.SevenZResource.java

/**
 * fetches information from the named entry inside the archive.
 *///  ww  w  .j av a  2  s.  c o m
protected void fetchEntry() {
    File f = getSevenZFile();
    if (f == null) {
        super.fetchEntry();
        return;
    }

    SevenZFile z = null;
    try {
        z = new SevenZFile(f);
        SevenZArchiveEntry ze = z.getNextEntry();
        while (ze != null) {
            if (ze.getName().equals(getName())) {
                setEntry(ze);
                return;
            }
            ze = z.getNextEntry();
        }
        setEntry(null);
    } catch (IOException e) {
        log(e.getMessage(), Project.MSG_DEBUG);
        throw new BuildException(e);
    } finally {
        if (z != null) {
            try {
                z.close();
            } catch (IOException ex) {
                // swallow
            }
        }
    }
}

From source file:org.apache.ant.compress.resources.SevenZScanner.java

/**
 * Fills the file and directory maps with resources read from the
 * archive./*from w  w w  .j  a  va2 s .  c om*/
 *
 * @param src the archive to scan.
 * @param encoding encoding used to encode file names inside the
 * archive - ignored.
 * @param fileEntries Map (name to resource) of non-directory
 * resources found inside the archive.
 * @param matchFileEntries Map (name to resource) of non-directory
 * resources found inside the archive that matched all include
 * patterns and didn't match any exclude patterns.
 * @param dirEntries Map (name to resource) of directory
 * resources found inside the archive.
 * @param matchDirEntries Map (name to resource) of directory
 * resources found inside the archive that matched all include
 * patterns and didn't match any exclude patterns.
 */
protected void fillMapsFromArchive(Resource src, String encoding, Map fileEntries, Map matchFileEntries,
        Map dirEntries, Map matchDirEntries) {

    FileProvider fp = (FileProvider) src.as(FileProvider.class);
    if (fp == null) {
        super.fillMapsFromArchive(src, encoding, fileEntries, matchFileEntries, dirEntries, matchDirEntries);
        return;
    }

    File srcFile = fp.getFile();
    SevenZArchiveEntry entry = null;
    SevenZFile zf = null;

    try {
        try {
            zf = new SevenZFile(srcFile);
            entry = zf.getNextEntry();
            while (entry != null) {
                /* TODO implement canReadEntryData in CC
                if (getSkipUnreadableEntries() && !zf.canReadEntryData(entry)) {
                log(Messages.skippedIsUnreadable(entry));
                continue;
                }
                */
                Resource r = new SevenZResource(srcFile, encoding, entry);
                String name = entry.getName();
                if (entry.isDirectory()) {
                    name = trimSeparator(name);
                    dirEntries.put(name, r);
                    if (match(name)) {
                        matchDirEntries.put(name, r);
                    }
                } else {
                    fileEntries.put(name, r);
                    if (match(name)) {
                        matchFileEntries.put(name, r);
                    }
                }
                entry = zf.getNextEntry();
            }
        } catch (IOException ex) {
            throw new BuildException("Problem opening " + srcFile, ex);
        }
    } finally {
        if (zf != null) {
            try {
                zf.close();
            } catch (IOException ex) {
                // swallow
            }
        }
    }
}

From source file:org.apache.ant.compress.taskdefs.Un7z.java

protected void expandFile(FileUtils fileUtils, File srcF, File dir) {
    if (!srcF.exists()) {
        throw new BuildException("Unable to expand " + srcF + " as the file does not exist", getLocation());
    }//from   w w  w.  ja  v  a2s  .co m
    log("Expanding: " + srcF + " into " + dir, Project.MSG_INFO);
    FileNameMapper mapper = getMapper();
    SevenZFile outer = null;
    try {
        final SevenZFile zf = outer = new SevenZFile(srcF);
        boolean empty = true;
        SevenZArchiveEntry ze = zf.getNextEntry();
        while (ze != null) {
            empty = false;
            /* TODO implement canReadEntryData in CC
            if (getSkipUnreadableEntries() && !zf.canReadEntryData(ze)) {
            log(Messages.skippedIsUnreadable(ze));
            continue;
            }
            */
            log("extracting " + ze.getName(), Project.MSG_DEBUG);
            InputStream is = null;
            try {
                extractFile(fileUtils, srcF, dir, is = new InputStream() {
                    public int read() throws IOException {
                        return zf.read();
                    }

                    public int read(byte[] b) throws IOException {
                        return zf.read(b);
                    }
                }, ze.getName(), ze.getLastModifiedDate(), ze.isDirectory(), mapper);
            } finally {
                FileUtils.close(is);
            }
            ze = zf.getNextEntry();
        }
        if (empty && getFailOnEmptyArchive()) {
            throw new BuildException("archive '" + srcF + "' is empty");
        }
        log("expand complete", Project.MSG_VERBOSE);
    } catch (IOException ioe) {
        throw new BuildException("Error while expanding " + srcF.getPath() + "\n" + ioe.toString(), ioe);
    } finally {
        if (outer != null) {
            try {
                outer.close();
            } catch (IOException ex) {
                // swallow
            }
        }
    }
}

From source file:org.apache.marmotta.loader.core.MarmottaLoader.java

public void loadArchive(File archive, LoaderHandler handler, RDFFormat format)
        throws RDFParseException, IOException, ArchiveException {
    log.info("loading files in archive {} ...", archive);

    if (archive.exists() && archive.canRead()) {

        if (archive.getName().endsWith("7z")) {
            log.info("auto-detected archive format: 7Z");

            final SevenZFile sevenZFile = new SevenZFile(archive);

            try {
                SevenZArchiveEntry entry;
                while ((entry = sevenZFile.getNextEntry()) != null) {

                    if (!entry.isDirectory()) {
                        log.info("loading entry {} ...", entry.getName());

                        // detect the file format
                        RDFFormat detectedFormat = Rio.getParserFormatForFileName(entry.getName());
                        if (format == null) {
                            if (detectedFormat != null) {
                                log.info("auto-detected entry format: {}", detectedFormat.getName());
                                format = detectedFormat;
                            } else {
                                throw new RDFParseException(
                                        "could not detect input format of entry " + entry.getName());
                            }//from ww  w . ja  v a  2 s.co m
                        } else {
                            if (detectedFormat != null && !format.equals(detectedFormat)) {
                                log.warn("user-specified entry format ({}) overrides auto-detected format ({})",
                                        format.getName(), detectedFormat.getName());
                            } else {
                                log.info("user-specified entry format: {}", format.getName());
                            }
                        }

                        load(new InputStream() {
                            @Override
                            public int read() throws IOException {
                                return sevenZFile.read();
                            }

                            @Override
                            public int read(byte[] b) throws IOException {
                                return sevenZFile.read(b);
                            }

                            @Override
                            public int read(byte[] b, int off, int len) throws IOException {
                                return sevenZFile.read(b, off, len);
                            }
                        }, handler, format);
                    }
                }
            } finally {
                sevenZFile.close();
            }

        } else {
            InputStream in;

            String archiveCompression = detectCompression(archive);
            InputStream fin = new BufferedInputStream(new FileInputStream(archive));
            if (archiveCompression != null) {
                if (CompressorStreamFactory.GZIP.equalsIgnoreCase(archiveCompression)) {
                    log.info("auto-detected archive compression: GZIP");
                    in = new GzipCompressorInputStream(fin, true);
                } else if (CompressorStreamFactory.BZIP2.equalsIgnoreCase(archiveCompression)) {
                    log.info("auto-detected archive compression: BZIP2");
                    in = new BZip2CompressorInputStream(fin, true);
                } else if (CompressorStreamFactory.XZ.equalsIgnoreCase(archiveCompression)) {
                    log.info("auto-detected archive compression: XZ");
                    in = new XZCompressorInputStream(fin, true);
                } else {
                    in = fin;
                }
            } else {
                in = fin;
            }

            ArchiveInputStream zipStream = new ArchiveStreamFactory()
                    .createArchiveInputStream(new BufferedInputStream(in));
            logArchiveType(zipStream);

            ArchiveEntry entry;
            while ((entry = zipStream.getNextEntry()) != null) {

                if (!entry.isDirectory()) {
                    log.info("loading entry {} ...", entry.getName());

                    // detect the file format
                    RDFFormat detectedFormat = Rio.getParserFormatForFileName(entry.getName());
                    if (format == null) {
                        if (detectedFormat != null) {
                            log.info("auto-detected entry format: {}", detectedFormat.getName());
                            format = detectedFormat;
                        } else {
                            throw new RDFParseException(
                                    "could not detect input format of entry " + entry.getName());
                        }
                    } else {
                        if (detectedFormat != null && !format.equals(detectedFormat)) {
                            log.warn("user-specified entry format ({}) overrides auto-detected format ({})",
                                    format.getName(), detectedFormat.getName());
                        } else {
                            log.info("user-specified entry format: {}", format.getName());
                        }
                    }

                    load(zipStream, handler, format);
                }
            }
        }

    } else {
        throw new RDFParseException(
                "could not load files from archive " + archive + ": it does not exist or is not readable");
    }

}

From source file:org.codehaus.plexus.archiver.sevenz.SevenZUnArchiver.java

protected void execute() throws ArchiverException {
    File source = getSourceFile();
    File dest = this.getDestDirectory();
    if (source.lastModified() > dest.lastModified()) {
        try {//from w  w w. j ava 2  s . c  om
            SevenZFile sevenZFile = new SevenZFile(source);
            SevenZArchiveEntry entry;
            FileOutputStream fos;
            byte[] bytes = new byte[1024];
            int read;
            long offset = 0;
            long size;
            while ((entry = sevenZFile.getNextEntry()) != null) {
                fos = new FileOutputStream(Paths.get(dest.getAbsolutePath(), entry.getName()).toFile());
                size = entry.getSize();
                do {
                    read = sevenZFile.read(bytes);
                    if (read > 0)
                        fos.write(bytes, 0, read);
                } while (size > offset && read > 0);
                fos.close();
            }
            sevenZFile.close();
        } catch (IOException ioe) {
            throw new ArchiverException(
                    "Problem unzipping 7z file " + source.getAbsolutePath() + " to " + dest.getAbsolutePath(),
                    ioe);
        }
    }
}

From source file:org.openjump.core.ui.plugin.file.open.OpenFileWizardState.java

public void setupFileLoaders(File[] files, FileLayerLoader fileLayerLoader) {
    Set<File> fileSet = new TreeSet<File>(Arrays.asList(files));
    multiLoaderFiles.clear();// ww w .  j  ava 2 s.  c o  m
    // explicit loader chosen
    if (fileLayerLoader != null) {
        fileLoaderMap.clear();
        for (File file : fileSet) {
            setFileLoader(file.toURI(), fileLayerLoader);
        }
    } else {
        // Remove old entries in fileloadermap
        fileLoaderMap.clear();
        //      for (Iterator<Entry<URI, FileLayerLoader>> iterator = fileLoaderMap.entrySet()
        //        .iterator(); iterator.hasNext();) {
        //        Entry<URI, FileLayerLoader> entry = iterator.next();
        //        URI fileUri = entry.getKey();
        //        File file;

        //        if (fileUri.getScheme().equals("zip")) {
        //          file = UriUtil.getZipFile(fileUri);
        //        } else {
        //          file = new File(fileUri);
        //        }
        //        
        //        if (!fileSet.contains(file)) {
        //          FileLayerLoader loader = entry.getValue();
        //          fileLoaderFiles.get(loader);
        //          Set<URI> loaderFiles = fileLoaderFiles.get(loader);
        //          if (loaderFiles != null) {
        //            loaderFiles.remove(fileUri);
        //          }
        //          iterator.remove();
        //        }
        //      }

        // manually add compressed files here
        for (File file : files) {
            // zip files
            if (CompressedFile.isZip(file.getName())) {
                try {
                    ZipFile zipFile = new ZipFile(file);
                    URI fileUri = file.toURI();
                    Enumeration entries = zipFile.getEntries();
                    while (entries.hasMoreElements()) {
                        ZipArchiveEntry entry = (ZipArchiveEntry) entries.nextElement();
                        if (!entry.isDirectory()) {
                            URI entryUri = UriUtil.createZipUri(file, entry.getName());
                            String entryExt = UriUtil.getFileExtension(entryUri);
                            //System.out.println(entryUri+"<->"+entryExt);
                            addFile(entryExt, entryUri);
                        }
                    }
                } catch (Exception e) {
                    errorHandler.handleThrowable(e);
                }
            }
            // tar[.gz,.bz...] (un)compressed archive files
            else if (CompressedFile.isTar(file.getName())) {
                try {
                    InputStream is = CompressedFile.openFile(file.getAbsolutePath(), null);
                    TarArchiveEntry entry;
                    TarArchiveInputStream tis = new TarArchiveInputStream(is);
                    while ((entry = tis.getNextTarEntry()) != null) {
                        if (!entry.isDirectory()) {
                            URI entryUri = UriUtil.createZipUri(file, entry.getName());

                            String entryExt = UriUtil.getFileExtension(entryUri);
                            addFile(entryExt, entryUri);
                        }
                    }
                    tis.close();
                } catch (Exception e) {
                    errorHandler.handleThrowable(e);
                }
            }
            // 7zip compressed files
            else if (CompressedFile.isSevenZ(file.getName())) {
                try {
                    //System.out.println(file.getName());
                    SevenZFile sevenZFile = new SevenZFile(file);
                    SevenZArchiveEntry entry;
                    while ((entry = sevenZFile.getNextEntry()) != null) {
                        if (!entry.isDirectory()) {
                            URI entryUri = UriUtil.createZipUri(file, entry.getName());

                            String entryExt = UriUtil.getFileExtension(entryUri);
                            addFile(entryExt, entryUri);
                        }
                    }
                    sevenZFile.close();
                } catch (IOException e) {
                    errorHandler.handleThrowable(e);
                }
            }
            // compressed files
            else if (CompressedFile.hasCompressedFileExtension(file.getName())) {
                String[] parts = file.getName().split("\\.");
                if (parts.length > 2)
                    addFile(parts[parts.length - 2], file.toURI());
            }
            // anything else is a plain data file
            else {
                URI fileUri = file.toURI();
                addFile(FileUtil.getExtension(file), fileUri);
            }
        }
    }
}