Example usage for java.util.zip ZipEntry ZipEntry

List of usage examples for java.util.zip ZipEntry ZipEntry

Introduction

In this page you can find the example usage for java.util.zip ZipEntry ZipEntry.

Prototype

public ZipEntry(ZipEntry e) 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

From source file:com.yifanlu.PSXperiaTool.ZpakCreate.java

public void create(boolean noCompress) throws IOException {
    Logger.info("Generating zpak file from directory %s with compression = %b", mDirectory.getPath(),
            !noCompress);/*from   w w  w . java  2  s.  c om*/
    IOFileFilter filter = new IOFileFilter() {
        public boolean accept(File file) {
            if (file.getName().startsWith(".")) {
                Logger.debug("Skipping file %s", file.getPath());
                return false;
            }
            return true;
        }

        public boolean accept(File file, String s) {
            if (s.startsWith(".")) {
                Logger.debug("Skipping file %s", file.getPath());
                return false;
            }
            return true;
        }
    };
    Iterator<File> it = FileUtils.iterateFiles(mDirectory, filter, TrueFileFilter.INSTANCE);
    ZipOutputStream out = new ZipOutputStream(mOut);
    out.setMethod(noCompress ? ZipEntry.STORED : ZipEntry.DEFLATED);
    while (it.hasNext()) {
        File current = it.next();
        FileInputStream in = new FileInputStream(current);
        ZipEntry zEntry = new ZipEntry(
                current.getPath().replace(mDirectory.getPath(), "").substring(1).replace("\\", "/"));
        if (noCompress) {
            zEntry.setSize(in.getChannel().size());
            zEntry.setCompressedSize(in.getChannel().size());
            zEntry.setCrc(getCRC32(current));
        }
        out.putNextEntry(zEntry);
        Logger.verbose("Adding file %s", current.getPath());
        int n;
        while ((n = in.read(mBuffer)) != -1) {
            out.write(mBuffer, 0, n);
        }
        in.close();
        out.closeEntry();
    }
    out.close();
    Logger.debug("Done with ZPAK creation.");
}

From source file:eu.openanalytics.rsb.message.MultiFilesResult.java

/**
 * Zips all the files contained in a multifiles result except if the result is
 * not successful, in that case returns the first file (which should be the only
 * one and contain a plain text error message).
 * /*from w w  w  .j a  va2 s  . com*/
 * @param result
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 */
public static File zipResultFilesIfNotError(final MultiFilesResult result)
        throws FileNotFoundException, IOException {
    final File[] resultFiles = result.getPayload();

    if ((!result.isSuccess()) && (resultFiles.length == 1)) {
        return resultFiles[0];
    }

    final File resultZipFile = new File(result.getTemporaryDirectory(), result.getJobId() + ".zip");
    final ZipOutputStream resultZOS = new ZipOutputStream(new FileOutputStream(resultZipFile));

    for (final File resultFile : resultFiles) {
        resultZOS.putNextEntry(new ZipEntry(resultFile.getName()));

        final FileInputStream fis = new FileInputStream(resultFile);
        IOUtils.copy(fis, resultZOS);
        IOUtils.closeQuietly(fis);

        resultZOS.closeEntry();
    }

    IOUtils.closeQuietly(resultZOS);
    return resultZipFile;
}

From source file:biz.c24.io.spring.batch.writer.source.ZipFileWriterSource.java

@Override
public void initialise(StepExecution stepExecution) {
    // Extract the name of the file we're supposed to be writing to
    String fileName = resource != null ? resource.getPath()
            : stepExecution.getJobParameters().getString("output.file");

    // Remove any leading file:// if it exists
    if (fileName.startsWith("file://")) {
        fileName = fileName.substring("file://".length());
    }//  w w  w. ja v  a 2 s. c  om

    // Now create the name of our zipEntry
    // Strip off the leading path and the suffix (ie the zip extension)
    int tailStarts = fileName.lastIndexOf(pathSepString) + 1;
    int tailEnds = fileName.lastIndexOf('.');
    if (tailStarts < 0) {
        tailStarts = 0;
    }
    if (tailEnds < 0) {
        tailEnds = fileName.length();
    }

    String tailName = fileName.substring(tailStarts, tailEnds);

    try {
        FileOutputStream fileStream = new FileOutputStream(fileName);
        zipStream = new ZipOutputStream(fileStream);
        zipStream.putNextEntry(new ZipEntry(tailName));
        outputWriter = new OutputStreamWriter(zipStream, getEncoding());
    } catch (IOException ioEx) {
        throw new RuntimeException(ioEx);
    }

}

From source file:com.joliciel.talismane.machineLearning.AbstractMachineLearningModel.java

@Override
public final void persist(File modelFile) {
    try {/*from   www . j av  a  2  s . c  o m*/
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(modelFile, false));
        Writer writer = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));

        zos.putNextEntry(new ZipEntry("algorithm.txt"));
        writer.write(this.getAlgorithm().name());
        writer.flush();
        zos.flush();

        for (String descriptorKey : descriptors.keySet()) {
            zos.putNextEntry(new ZipEntry(descriptorKey + "_descriptors.txt"));
            List<String> descriptorList = descriptors.get(descriptorKey);
            for (String descriptor : descriptorList) {
                writer.write(descriptor + "\n");
                writer.flush();
            }
            zos.flush();

        }

        zos.putNextEntry(new ZipEntry("attributes.txt"));
        for (String name : this.modelAttributes.keySet()) {
            String value = this.modelAttributes.get(name);
            writer.write(name + "\t" + value + "\n");
            writer.flush();
        }

        for (String name : this.dependencies.keySet()) {
            Object dependency = this.dependencies.get(name);
            zos.putNextEntry(new ZipEntry(name + "_dependency.obj"));
            ObjectOutputStream oos = new ObjectOutputStream(zos);
            try {
                oos.writeObject(dependency);
            } finally {
                oos.flush();
            }
            zos.flush();
        }

        this.persistOtherEntries(zos);

        if (this.externalResources != null) {
            zos.putNextEntry(new ZipEntry("externalResources.obj"));
            ObjectOutputStream oos = new ObjectOutputStream(zos);
            try {
                oos.writeObject(externalResources);
            } finally {
                oos.flush();
            }
            zos.flush();
        }

        this.writeDataToStream(zos);

        zos.putNextEntry(new ZipEntry("model.bin"));
        this.writeModelToStream(zos);
        zos.flush();

        zos.close();
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    }
}

From source file:io.lightlink.excel.StreamingExcelTransformer.java

public void doExport(InputStream template, OutputStream out, ExcelStreamVisitor visitor) throws IOException {
    try {//from  w w w.jav a 2  s . c om
        ZipInputStream zipIn = new ZipInputStream(template);
        ZipOutputStream zipOut = new ZipOutputStream(out);

        ZipEntry entry;

        Map<String, byte[]> sheets = new HashMap<String, byte[]>();

        while ((entry = zipIn.getNextEntry()) != null) {

            String name = entry.getName();

            if (name.startsWith("xl/sharedStrings.xml")) {

                byte[] bytes = IOUtils.toByteArray(zipIn);
                zipOut.putNextEntry(new ZipEntry(name));
                zipOut.write(bytes);

                sharedStrings = processSharedStrings(bytes);

            } else if (name.startsWith("xl/worksheets/sheet")) {
                byte[] bytes = IOUtils.toByteArray(zipIn);
                sheets.put(name, bytes);
            } else if (name.equals("xl/calcChain.xml")) {
                // skip this file, let excel recreate it
            } else if (name.equals("xl/workbook.xml")) {
                zipOut.putNextEntry(new ZipEntry(name));

                SAXParserFactory factory = SAXParserFactory.newInstance();
                SAXParser saxParser = factory.newSAXParser();
                Writer writer = new OutputStreamWriter(zipOut, "UTF-8");

                byte[] bytes = IOUtils.toByteArray(zipIn);
                saxParser.parse(new ByteArrayInputStream(bytes), new WorkbookTemplateHandler(writer));

                writer.flush();
            } else {
                zipOut.putNextEntry(new ZipEntry(name));
                IOUtils.copy(zipIn, zipOut);
            }

        }

        for (Map.Entry<String, byte[]> sheetEntry : sheets.entrySet()) {
            String name = sheetEntry.getKey();

            byte[] bytes = sheetEntry.getValue();
            zipOut.putNextEntry(new ZipEntry(name));
            processSheet(bytes, zipOut, visitor);
        }

        zipIn.close();
        template.close();

        zipOut.close();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.toString(), e);
    }
}

From source file:ch.ivyteam.ivy.maven.util.ClasspathJar.java

private void writeManifest(String name, ZipOutputStream jarStream, List<String> classpathEntries)
        throws IOException {
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    manifest.getMainAttributes().putValue("Name", name);
    if (mainClass != null) {
        manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, mainClass);
    }//w w w.j  a  v  a  2 s . c  o m
    if (!classpathEntries.isEmpty()) {
        manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, StringUtils.join(classpathEntries, " "));
    }
    jarStream.putNextEntry(new ZipEntry(MANIFEST_MF));
    manifest.write(jarStream);
}

From source file:net.firejack.platform.core.utils.ArchiveUtils.java

public static void zip(OutputStream outputStream, Map<String, InputStream> filePaths) throws IOException {
    ZipOutputStream out = new ZipOutputStream(outputStream);

    for (Map.Entry<String, InputStream> file : filePaths.entrySet()) {
        String filename = file.getKey();
        InputStream stream = file.getValue();
        if (stream != null) {
            System.out.println("Adding: " + filename);
            ZipEntry entry = new ZipEntry(filename);
            out.putNextEntry(entry);//from ww w . j  a  va 2  s .  co  m
            IOUtils.copy(stream, out);
            stream.close();
        }
    }

    out.close();
}

From source file:com.aionlightning.slf4j.conversion.TruncateToZipFileAppender.java

/**
 * This method creates archive with file instead of deleting it.
 * // www  .  j a v a2  s . co m
 * @param file
 *            file to truncate
 */
protected void truncate(File file) {
    File backupRoot = new File(backupDir);
    if (!backupRoot.exists() && !backupRoot.mkdirs()) {
        log.warn("Can't create backup dir for backup storage");
        return;
    }

    String date = "";
    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        date = reader.readLine().split("\f")[1];
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");
    ZipOutputStream zos = null;
    FileInputStream fis = null;
    try {
        zos = new ZipOutputStream(new FileOutputStream(zipFile));
        ZipEntry entry = new ZipEntry(file.getName());
        entry.setMethod(ZipEntry.DEFLATED);
        entry.setCrc(FileUtils.checksumCRC32(file));
        zos.putNextEntry(entry);
        fis = FileUtils.openInputStream(file);

        byte[] buffer = new byte[1024];
        int readed;
        while ((readed = fis.read(buffer)) != -1) {
            zos.write(buffer, 0, readed);
        }

    } catch (Exception e) {
        log.warn("Can't create zip file", e);
    } finally {
        if (zos != null) {
            try {
                zos.close();
            } catch (IOException e) {
                log.warn("Can't close zip file", e);
            }
        }

        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                log.warn("Can't close zipped file", e);
            }
        }
    }

    if (!file.delete()) {
        log.warn("Can't delete old log file " + file.getAbsolutePath());
    }
}

From source file:com.jaxio.celerio.output.ZipOutputResult.java

@Override
public void addContent(byte[] contentBytes, String entryName, TemplatePack pack, Template template)
        throws IOException {
    open();// ww  w .j  a  va  2 s.c  om
    if (fileList.contains(entryName)) {
        log.error("Ignore duplicate entry: " + entryName);
        return;
    } else {
        fileList.add(entryName);
    }

    // Add archive entry
    ZipEntry zipEntry = new ZipEntry(normalize(entryName));
    zipOutputStream.putNextEntry(zipEntry);
    zipOutputStream.write(contentBytes, 0, contentBytes.length);
}

From source file:au.com.permeance.liferay.util.zip.ZipWriter.java

public void addEntry(String path, InputStream is) throws IOException {
    this.zos.putNextEntry(new ZipEntry(path));
    StreamUtil.transfer(is, zos, false);
    this.allocatedPaths.add(path);
}