Example usage for java.util.zip ZipOutputStream ZipOutputStream

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

Introduction

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

Prototype

public ZipOutputStream(OutputStream out) 

Source Link

Document

Creates a new ZIP output stream.

Usage

From source file:com.twinsoft.convertigo.engine.util.ZipUtils.java

public static void makeZip(String archiveFileName, String sDir, String sRelativeDir, List<File> excludedFiles)
        throws Exception {
    FileOutputStream fos = new FileOutputStream(archiveFileName);
    ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
    int nbZipEntries = ZipUtils.putEntries(zos, sDir, sRelativeDir, excludedFiles);
    if (nbZipEntries > 0)
        zos.close();//from  w  ww . ja  v a 2 s .  c o m
}

From source file:com.ibm.watson.developer_cloud.retrieve_and_rank.v1.util.ZipUtils.java

/**
 * Builds the configuration ZIP file./* w w w.j a  v  a2s  .  c om*/
 * 
 * @param configName the configuration name
 * @param parentDir the parent directory
 * @return the file
 */
public static File buildConfigZip(final String configName, final File parentDir) {
    if (!parentDir.isDirectory()) {
        throw new RuntimeException(MSGS.format(CONFIG_NOT_DIR_1, parentDir.toString()));
    }

    final File zipFile = createEmptyZipFile(configName);
    final ZipOutputStream out;
    try {
        out = new ZipOutputStream(new FileOutputStream(zipFile));
    } catch (final FileNotFoundException e) {
        throw new RuntimeException(MSGS.format(ERROR_ZIPPING_1, parentDir.toString()), e);
    }

    try {
        addFilesToZip(parentDir, out, parentDir);
        return zipFile;
    } catch (final IOException e) {
        throw new RuntimeException(MSGS.format(ERROR_ZIPPING_1, parentDir.toString()), e);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:net.grinder.util.LogCompressUtils.java

/**
 * Compress multiple Files with the given encoding.
 *
 * @param logFiles     files to be compressed
 * @param fromEncoding log file encoding
 * @param toEncoding   compressed log file encoding
 * @return compressed file byte array/*from w w w. ja  v  a 2  s. c o  m*/
 */
public static byte[] compress(File[] logFiles, Charset fromEncoding, Charset toEncoding) {
    FileInputStream fis = null;
    InputStreamReader isr = null;
    ByteArrayOutputStream out = null;
    ZipOutputStream zos = null;
    OutputStreamWriter osw = null;
    if (toEncoding == null) {
        toEncoding = Charset.defaultCharset();
    }
    if (fromEncoding == null) {
        fromEncoding = Charset.defaultCharset();
    }
    try {
        out = new ByteArrayOutputStream();
        zos = new ZipOutputStream(out);
        osw = new OutputStreamWriter(zos, toEncoding);
        for (File each : logFiles) {
            try {
                fis = new FileInputStream(each);
                isr = new InputStreamReader(fis, fromEncoding);
                ZipEntry zipEntry = new ZipEntry(each.getName());
                zipEntry.setTime(each.lastModified());
                zos.putNextEntry(zipEntry);
                char[] buffer = new char[COMPRESS_BUFFER_SIZE];
                int count;
                while ((count = isr.read(buffer, 0, COMPRESS_BUFFER_SIZE)) != -1) {
                    osw.write(buffer, 0, count);
                }
                osw.flush();
                zos.flush();
                zos.closeEntry();
            } catch (IOException e) {
                LOGGER.error("Error occurs while compressing {} : {}", each.getAbsolutePath(), e.getMessage());
                LOGGER.debug("Details ", e);
            } finally {
                IOUtils.closeQuietly(isr);
                IOUtils.closeQuietly(fis);
            }
        }
        zos.finish();
        zos.flush();
        return out.toByteArray();
    } catch (IOException e) {
        LOGGER.error("Error occurs while compressing log : {} ", e.getMessage());
        LOGGER.debug("Details : ", e);
        return null;
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(osw);
    }
}

From source file:com.google.refine.model.medadata.PackageExtension.java

/**
 * Do the package since the final spec for the compression/bundle are not settled yet.
 * https://github.com/frictionlessdata/datapackage-js/issues/93
 * //from ww w. ja  v a 2s  . c  o m
 * @param pkg Package 
 * @param dataByteArrayOutputStream  ByteArrayOutputStream
 * @param destOs OutputStream
 * @throws IOException 
 * @throws FileNotFoundException 
 * @see Package#saveZip(String outputFilePath) 
 */
public static void saveZip(Package pkg, final ByteArrayOutputStream dataByteArrayOutputStream,
        final OutputStream destOs) throws FileNotFoundException, IOException {
    try (ZipOutputStream zos = new ZipOutputStream(destOs)) {
        // json file 
        ZipEntry entry = new ZipEntry(DataPackageMetadata.DEFAULT_FILE_NAME);
        zos.putNextEntry(entry);
        zos.write(pkg.getJson().toString(JSON_INDENT_FACTOR).getBytes());
        zos.closeEntry();
        // default data file to data.csv or given path(can only handle one file because files cannot be restored)
        String path = (String) pkg.getResources().get(0).getPath();
        entry = new ZipEntry(StringUtils.isBlank(path) ? "data.csv" : path);
        zos.putNextEntry(entry);
        zos.write(dataByteArrayOutputStream.toByteArray());
        zos.closeEntry();
    }
}

From source file:com.ftb2om2.util.Zipper.java

public void createOSZ(String mp3Path, String outputPath, List<Difficulty> difficulty) throws IOException {
    FileOutputStream fos = new FileOutputStream(
            outputPath + "\\" + FilenameUtils.getBaseName(mp3Path) + ".osz");
    ZipOutputStream zos = new ZipOutputStream(fos);

    addToZip(mp3Path, "Audio.mp3", zos);

    difficulty.forEach(file -> {//from   w  w  w .  j  av a2  s.co  m
        try {
            addToZip(outputPath + "\\" + file.getDifficultyName() + ".osu", file.getDifficultyName() + ".osu",
                    zos);
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    });

    zos.close();
    fos.close();
}

From source file:Compress.java

/** Zip the contents of the directory, and save it in the zipfile */
public static void zipDirectory(String dir, String zipfile) throws IOException, IllegalArgumentException {
    // Check that the directory is a directory, and get its contents
    File d = new File(dir);
    if (!d.isDirectory())
        throw new IllegalArgumentException("Compress: not a directory:  " + dir);
    String[] entries = d.list();//from  ww w. java2 s  .  c o m
    byte[] buffer = new byte[4096]; // Create a buffer for copying
    int bytes_read;

    // Create a stream to compress data and write it to the zipfile
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));

    // Loop through all entries in the directory
    for (int i = 0; i < entries.length; i++) {
        File f = new File(d, entries[i]);
        if (f.isDirectory())
            continue; // Don't zip sub-directories
        FileInputStream in = new FileInputStream(f); // Stream to read file
        ZipEntry entry = new ZipEntry(f.getPath()); // Make a ZipEntry
        out.putNextEntry(entry); // Store entry
        while ((bytes_read = in.read(buffer)) != -1)
            // Copy bytes
            out.write(buffer, 0, bytes_read);
        in.close(); // Close input stream
    }
    // When we're done with the whole loop, close the output stream
    out.close();
}

From source file:b2s.idea.mavenize.JarCombiner.java

public void combineAllJarsIn(File folderOfJars, File output) {
    ZipOutputStream zipOut = null;
    try {/*from w  w w  .j  a  v  a 2s .  c  o m*/
        JarContext context = new JarContext();
        zipOut = new ZipOutputStream(new FileOutputStream(output));
        for (File jarFile : folderOfJars.listFiles(new IntellijJarFileFilter())) {
            copyContentsOf(jarFile, zipOut, context);
            System.out.println(jarFile.getName());
        }

        addServiceEntries(zipOut, context);

        zipOut.finish();
    } catch (IOException e) {
        throw new RuntimeException("A problem occurred when combining the JARs", e);
    } finally {
        IOUtils.closeQuietly(zipOut);
    }
}

From source file:cc.recommenders.utils.Zips.java

public static void zip(File directory, File out) throws IOException {
    ZipOutputStream zos = null;//  w w  w  .  j  a v  a2s. c o m
    try {
        OutputSupplier<FileOutputStream> s = Files.newOutputStreamSupplier(out);
        zos = new ZipOutputStream(s.getOutput());
        Collection<File> files = FileUtils.listFiles(directory, FILE, DIRECTORY);
        for (File f : files) {
            String path = removeStart(f.getPath(), directory.getAbsolutePath() + "/");
            ZipEntry e = new ZipEntry(path);
            zos.putNextEntry(e);
            byte[] data = Files.toByteArray(f);
            zos.write(data);
            zos.closeEntry();
        }
    } finally {
        Closeables.close(zos, false);
    }
}

From source file:com.facebook.buck.util.zip.ZipScrubberTest.java

@Test
public void modificationTimes() throws Exception {

    // Create a dummy ZIP file.
    ByteArrayOutputStream bytesOutputStream = new ByteArrayOutputStream();
    try (ZipOutputStream out = new ZipOutputStream(bytesOutputStream)) {
        ZipEntry entry = new ZipEntry("file1");
        byte[] data = "data1".getBytes(Charsets.UTF_8);
        entry.setSize(data.length);/*from   ww w .ja  v a 2s. c  o m*/
        out.putNextEntry(entry);
        out.write(data);
        out.closeEntry();

        entry = new ZipEntry("file2");
        data = "data2".getBytes(Charsets.UTF_8);
        entry.setSize(data.length);
        out.putNextEntry(entry);
        out.write(data);
        out.closeEntry();
    }

    byte[] bytes = bytesOutputStream.toByteArray();
    // Execute the zip scrubber step.
    ZipScrubber.scrubZipBuffer(bytes.length, ByteBuffer.wrap(bytes));

    // Iterate over each of the entries, expecting to see all zeros in the time fields.
    Date dosEpoch = new Date(ZipUtil.dosToJavaTime(ZipConstants.DOS_FAKE_TIME));
    try (ZipInputStream is = new ZipInputStream(new ByteArrayInputStream(bytes))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            assertThat(entry.getName(), new Date(entry.getTime()), Matchers.equalTo(dosEpoch));
        }
    }
}

From source file:com.perrier.music.entity.album.AlbumZipper.java

public File zip(Album album) throws IOException {

    Path zipPath = Files.createTempFile(ZIP_PREFIX + album.getId() + "-", ".zip");
    File zipFile = zipPath.toFile();

    try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
        List<Track> tracks = album.getTracks();
        for (Track t : tracks) {
            String name = createFileName(t);
            ZipEntry zipEntry = new ZipEntry(name);
            zos.putNextEntry(zipEntry);/* w  w w  .ja va  2  s .c om*/

            try (InputStream audioStream = this.storageService.getAudioStream(t.getAudioStorageKey())) {
                IOUtils.copy(audioStream, zos);
            }
        }
    }

    return zipFile;
}