Example usage for java.util.zip ZipOutputStream putNextEntry

List of usage examples for java.util.zip ZipOutputStream putNextEntry

Introduction

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

Prototype

public void putNextEntry(ZipEntry e) throws IOException 

Source Link

Document

Begins writing a new ZIP file entry and positions the stream to the start of the entry data.

Usage

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

/**
 * This method creates archive with file instead of deleting it.
 * /*from w  ww  .j a v  a  2s  .c o  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:gov.nasa.ensemble.resources.ResourceUtil.java

public static void zipContainer(final IContainer container, final OutputStream os,
        final IProgressMonitor monitor) throws CoreException {
    final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(os));
    container.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    // monitor.beginTask("Zipping " + container.getName(), container.get);
    container.accept(new IResourceVisitor() {
        @Override/*from w w w.  j a  v  a  2 s .c om*/
        public boolean visit(IResource resource) throws CoreException {
            // MSLICE-1258
            for (IProjectPublishFilter filter : publishFilters)
                if (!filter.shouldInclude(resource))
                    return true;

            if (resource instanceof IFile) {
                final IFile file = (IFile) resource;
                final IPath relativePath = ResourceUtil.getRelativePath(container, file).some();
                final ZipEntry entry = new ZipEntry(relativePath.toString());
                try {
                    out.putNextEntry(entry);
                    out.write(ResourceUtil.getContents(file));
                    out.closeEntry();
                } catch (IOException e) {
                    throw new CoreException(new Status(IStatus.ERROR, EnsembleResourcesPlugin.PLUGIN_ID,
                            "Failed to write contents of " + file.getName(), e));
                }
            } else if (resource instanceof IFolder) {
                final IFolder folder = (IFolder) resource;
                if (folder.members().length > 0)
                    return true;
                final IPath relativePath = ResourceUtil.getRelativePath(container, folder).some();
                final ZipEntry entry = new ZipEntry(relativePath.toString() + "/");
                try {
                    out.putNextEntry(entry);
                    out.closeEntry();
                } catch (IOException e) {
                    LogUtil.error(e);
                    throw new CoreException(new Status(IStatus.ERROR, EnsembleResourcesPlugin.PLUGIN_ID,
                            "Failed to compress directory " + folder.getName(), e));
                }
            }
            return true;
        }
    });
    try {
        out.close();
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, EnsembleResourcesPlugin.PLUGIN_ID,
                "Failed to close output stream", e));
    }
}

From source file:de.uniwue.info6.database.jaxb.ScenarioExporter.java

/**
 *
 *
 * @param files//from w  w  w  .  j  av a2  s  . c om
 * @param zipfile
 * @return
 */
private File zip(List<File> files, File zipfile) {
    byte[] buf = new byte[1024];
    try {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
        for (int i = 0; i < files.size(); i++) {
            FileInputStream in = new FileInputStream(files.get(i));
            out.putNextEntry(new ZipEntry(files.get(i).getName()));
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.closeEntry();
            in.close();
        }
        out.close();
        for (File file : files) {
            if (file.isFile() && file.exists() && file.canWrite()) {
                file.delete();
            }
        }
        return zipfile;
    } catch (Exception e) {
        LOGGER.error("FAILED TO ZIP FILES", e);
    }
    return null;
}

From source file:com.music.scheduled.BackupJob.java

private void zipBackup(String baseFileName) throws IOException {
    FileOutputStream fos = new FileOutputStream(baseFileName + ".zip");
    ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));

    File entryFile = new File(baseFileName + ".sql");
    FileInputStream fi = new FileInputStream(entryFile);
    InputStream origin = new BufferedInputStream(fi, ZIP_BUFFER);
    ZipEntry entry = new ZipEntry("data.sql");
    zos.putNextEntry(entry);
    int count;/*  w  w w  .  j  a v  a2s .co  m*/
    byte[] data = new byte[ZIP_BUFFER];
    while ((count = origin.read(data, 0, ZIP_BUFFER)) != -1) {
        zos.write(data, 0, count);
    }
    origin.close();
    zos.close();

    entryFile.delete();
}

From source file:eu.delving.services.controller.DataSetController.java

private void writeSipZip(String dataSetSpec, OutputStream outputStream, String accessKey) throws IOException,
        MappingNotFoundException, AccessKeyException, XMLStreamException, MetadataException, MappingException {
    MetaRepo.DataSet dataSet = metaRepo.getDataSet(dataSetSpec);
    if (dataSet == null) {
        throw new IOException("Data Set not found"); // IOException?
    }//from w  w  w.  j a va  2  s.  c om
    ZipOutputStream zos = new ZipOutputStream(outputStream);
    zos.putNextEntry(new ZipEntry(FileStore.FACTS_FILE_NAME));
    Facts facts = Facts.fromBytes(dataSet.getDetails().getFacts());
    facts.setDownloadedSource(true);
    zos.write(Facts.toBytes(facts));
    zos.closeEntry();
    zos.putNextEntry(new ZipEntry(FileStore.SOURCE_FILE_NAME));
    String sourceHash = writeSourceStream(dataSet, zos, accessKey);
    zos.closeEntry();
    for (MetaRepo.Mapping mapping : dataSet.mappings().values()) {
        RecordMapping recordMapping = mapping.getRecordMapping();
        zos.putNextEntry(
                new ZipEntry(String.format(FileStore.MAPPING_FILE_PATTERN, recordMapping.getPrefix())));
        RecordMapping.write(recordMapping, zos);
        zos.closeEntry();
    }
    zos.finish();
    zos.close();
    dataSet.setSourceHash(sourceHash, true);
    dataSet.save();
}

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

@Override
public final void persist(File modelFile) {
    try {/*from w ww  . ja v  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:com.yunmel.syncretic.utils.io.IOUtils.java

/**
 * ZIP?// w  ww . j  a  v a2s  . c o  m
 * 
 * @param dirPath 
 * @param file 
 * @param zouts ?
 */
public static void zipFilesToZipFile(String dirPath, File file, ZipOutputStream zouts) {
    FileInputStream fin = null;
    ZipEntry entry = null;
    // ?
    byte[] buf = new byte[4096];
    int readByte = 0;
    if (file.isFile()) {
        try {
            // ?
            fin = new FileInputStream(file);
            // ZipEntry
            entry = new ZipEntry(getEntryName(dirPath, file));
            // ?
            zouts.putNextEntry(entry);
            // ?
            while ((readByte = fin.read(buf)) != -1) {
                zouts.write(buf, 0, readByte);
            }
            zouts.closeEntry();
            fin.close();
            System.out.println(" " + file.getAbsolutePath() + " zip!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

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

/**
 * @param basePath//from   ww w .  ja v a 2s.com
 * @param zipPath
 * @param filePaths
 * @throws java.io.IOException
 */
public static void zip(File basePath, File zipPath, Map<String, String> filePaths) throws IOException {
    BufferedInputStream origin = null;
    ZipOutputStream out = null;
    FileOutputStream dest = null;
    try {
        dest = new FileOutputStream(zipPath);
        out = new ZipOutputStream(new BufferedOutputStream(dest));
        //out.setMethod(ZipOutputStream.DEFLATED);
        byte data[] = new byte[BUFFER];
        for (Map.Entry<String, String> file : filePaths.entrySet()) {
            String filename = file.getKey();
            String filePath = file.getValue();
            System.out.println("Adding: " + basePath.getPath() + filePath + " => " + filename);
            File f = new File(basePath, filePath);
            if (f.exists()) {
                FileInputStream fi = new FileInputStream(f);
                origin = new BufferedInputStream(fi, BUFFER);
                ZipEntry entry = new ZipEntry(filename);
                entry.setCrc(FileUtils.checksumCRC32(new File(basePath, filePath)));
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
                origin.close();
            }
        }
    } finally {
        if (origin != null)
            origin.close();
        if (out != null)
            out.close();
        if (dest != null)
            dest.close();
    }
}

From source file:com.replaymod.sponge.recording.AbstractRecorder.java

@Override
public void endRecording(OutputStream out, ReplayMetaData metaData) throws IllegalStateException, IOException {
    if (metaData == null) {
        Preconditions.checkState(rawOutputs.remove(out),
                "Specified output is unknown or meta data is missing.");
        out.flush();/*from   w  w  w  .  j a  v  a 2 s  . c  o m*/
        out.close();
    } else {
        ZipOutputStream zipOut = outputs.remove(out);
        if (zipOut == null) {
            throw new IllegalStateException("Specified output is unknown or contains raw data.");
        }

        zipOut.closeEntry();

        zipOut.putNextEntry(new ZipEntry("metaData.json"));
        zipOut.write(toJson(metaData).getBytes());
        zipOut.closeEntry();

        zipOut.flush();
        zipOut.close();
    }
}

From source file:com.taobao.android.builder.tools.zip.ZipUtils.java

/**
 * zip/* w w  w. j ava 2s .c om*/
 *
 * @param zipFile
 * @param file
 * @param destPath
 * @param overwrite ?
 * @throws java.io.IOException
 */
public static void addFileToZipFile(File zipFile, File outZipFile, File file, String destPath,
        boolean overwrite) throws IOException {
    byte[] buf = new byte[1024];
    ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outZipFile));
    ZipEntry entry = zin.getNextEntry();
    boolean addFile = true;
    while (entry != null) {
        boolean addEntry = true;
        String name = entry.getName();
        if (StringUtils.equalsIgnoreCase(name, destPath)) {
            if (overwrite) {
                addEntry = false;
            } else {
                addFile = false;
            }
        }
        if (addEntry) {
            ZipEntry zipEntry = null;
            if (STORED == entry.getMethod()) {
                zipEntry = new ZipEntry(entry);
            } else {
                zipEntry = new ZipEntry(name);
            }
            out.putNextEntry(zipEntry);
            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }

    if (addFile) {
        InputStream in = new FileInputStream(file);
        // Add ZIP entry to output stream.
        ZipEntry zipEntry = new ZipEntry(destPath);
        out.putNextEntry(zipEntry);
        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        // Complete the entry
        out.closeEntry();
        in.close();
    }
    // Close the streams
    zin.close();
    out.close();
}