Java Code Examples for java.util.zip.ZipOutputStream#setMethod()

The following examples show how to use java.util.zip.ZipOutputStream#setMethod() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InsertHelperTest.java    From fastods with GNU General Public License v3.0 6 votes vote down vote up
private byte[] createAlmostEmptyZipFile(final byte[] content) throws IOException {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
    final ZipOutputStream zos = new ZipOutputStream(bos);
    zos.setMethod(ZipOutputStream.DEFLATED);
    zos.setLevel(0);
    for (final String name : Arrays
            .asList(ManifestElement.META_INF_MANIFEST_XML, "mimetype", "Thumbnails",
                    "content.xml")) {
        final ZipEntry e = new ZipEntry(name);
        zos.putNextEntry(e);
        zos.write(content);
    }
    zos.finish();
    zos.close();
    return bos.toByteArray();
}
 
Example 2
Source File: AbstractZip.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 *
 */
public void zipEntries(OutputStream os) throws IOException
{
	ZipOutputStream zipos = new ZipOutputStream(os);
	zipos.setMethod(ZipOutputStream.DEFLATED);
	
	for (String name : exportZipEntries.keySet()) 
	{
		ExportZipEntry exportZipEntry = exportZipEntries.get(name);
		ZipEntry zipEntry = new ZipEntry(exportZipEntry.getName());
		zipos.putNextEntry(zipEntry);
		exportZipEntry.writeData(zipos);
	}
	
	zipos.flush();
	zipos.finish();
}
 
Example 3
Source File: FileUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * For an inputStream and a file name, create a zip stream containing only one entry with the inputStream set to fileName
 * If fileName is empty, generate a unique one.
 *
 * @param fileStream
 * @param fileName
 * @return
 * @throws IOException
 */
public static ByteArrayInputStream zipFileStream(InputStream fileStream, String fileName) throws IOException {
    if (fileStream == null) return null;
    if (fileName == null) fileName = UUID.randomUUID().toString();
    // Create zip file from content input stream
    String zipFileName = UUID.randomUUID().toString() + ".zip";
    String zipFilePath = UtilProperties.getPropertyValue("general", "http.upload.tmprepository", "runtime/tmp");
    FileOutputStream fos = new FileOutputStream(new File(zipFilePath, zipFileName));
    ZipOutputStream zos = new ZipOutputStream(fos);
    zos.setMethod(ZipOutputStream.DEFLATED);
    zos.setLevel(Deflater.BEST_COMPRESSION);
    ZipEntry ze = new ZipEntry(fileName);
    zos.putNextEntry(ze);
    int len;
    byte[] bufferData = new byte[8192];
    while ((len = fileStream.read(bufferData)) > 0) {
        zos.write(bufferData, 0, len);
    }
    zos.closeEntry();
    zos.close();
    fos.close();

    //prepare zip stream
    File tmpZipFile = new File(zipFilePath, zipFileName);
    ByteArrayInputStream zipStream = new ByteArrayInputStream(FileUtils.readFileToByteArray(tmpZipFile));

    //Then delete zip file
    tmpZipFile.delete();
    return zipStream;
}
 
Example 4
Source File: OdsArchiveExplorerTest.java    From fastods with GNU General Public License v3.0 5 votes vote down vote up
private byte[] createArchiveAsBytes() throws IOException {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
    final ZipOutputStream zos = new ZipOutputStream(bos);
    zos.setMethod(ZipOutputStream.DEFLATED);
    zos.setLevel(0);
    zos.putNextEntry(new ZipEntry("temp1"));
    zos.write(1);
    zos.putNextEntry(new ZipEntry(ManifestElement.META_INF_MANIFEST_XML));
    zos.write(MANIFEST.getBytes(CharsetUtil.UTF_8));
    zos.putNextEntry(new ZipEntry("temp2"));
    zos.write(2);
    zos.finish();
    zos.close();
    return bos.toByteArray();
}
 
Example 5
Source File: DownloadController.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Downloads the given files.  The files are packed together in an
 * uncompressed zip-file.
 *
 *
 * @param response    The HTTP response.
 * @param status      The download status.
 * @param files       The files to download.
 * @param indexes     Only download songs at these indexes. May be <code>null</code>.
 * @param coverArtFile The cover art file to include, may be {@code null}.
 *@param range       The byte range, may be <code>null</code>.
 * @param zipFileName The name of the resulting zip file.   @throws IOException If an I/O error occurs.
 */
private void downloadFiles(HttpServletResponse response, TransferStatus status, List<MediaFile> files, int[] indexes, File coverArtFile, HttpRange range, String zipFileName) throws IOException {
    if (indexes != null && indexes.length == 1) {
        downloadFile(response, status, files.get(indexes[0]).getFile(), range);
        return;
    }

    LOG.info("Starting to download '" + zipFileName + "' to " + status.getPlayer());
    response.setContentType("application/x-download");
    response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodeAsRFC5987(zipFileName));

    ZipOutputStream out = new ZipOutputStream(RangeOutputStream.wrap(response.getOutputStream(), range));
    out.setMethod(ZipOutputStream.STORED);  // No compression.

    List<MediaFile> filesToDownload = new ArrayList<MediaFile>();
    if (indexes == null) {
        filesToDownload.addAll(files);
    } else {
        for (int index : indexes) {
            try {
                filesToDownload.add(files.get(index));
            } catch (IndexOutOfBoundsException x) { /* Ignored */}
        }
    }

    for (MediaFile mediaFile : filesToDownload) {
        zip(out, mediaFile.getParentFile(), mediaFile.getFile(), status, range);
    }
    if (coverArtFile != null && coverArtFile.exists()) {
        zip(out, coverArtFile.getParentFile(), coverArtFile, status, range);
    }


    out.close();
    LOG.info("Downloaded '" + zipFileName + "' to " + status.getPlayer());
}
 
Example 6
Source File: UnitTestZipArchive.java    From archive-patcher with Apache License 2.0 5 votes vote down vote up
/**
 * Make an arbitrary zip archive in memory using the specified entries.
 * @param entriesInFileOrder the entries
 * @return the zip file described above, as a byte array
 */
public static byte[] makeTestZip(List<UnitTestZipEntry> entriesInFileOrder) {
  try {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    ZipOutputStream zipOut = new ZipOutputStream(buffer);
    for (UnitTestZipEntry unitTestEntry : entriesInFileOrder) {
      ZipEntry zipEntry = new ZipEntry(unitTestEntry.path);
      zipOut.setLevel(unitTestEntry.level);
      CRC32 crc32 = new CRC32();
      byte[] uncompressedContent = unitTestEntry.getUncompressedBinaryContent();
      crc32.update(uncompressedContent);
      zipEntry.setCrc(crc32.getValue());
      zipEntry.setSize(uncompressedContent.length);
      if (unitTestEntry.level == 0) {
        zipOut.setMethod(ZipOutputStream.STORED);
        zipEntry.setCompressedSize(uncompressedContent.length);
      } else {
        zipOut.setMethod(ZipOutputStream.DEFLATED);
      }
      // Normalize MSDOS date/time fields to zero for reproducibility.
      zipEntry.setTime(0);
      if (unitTestEntry.comment != null) {
        zipEntry.setComment(unitTestEntry.comment);
      }
      zipOut.putNextEntry(zipEntry);
      zipOut.write(unitTestEntry.getUncompressedBinaryContent());
      zipOut.closeEntry();
    }
    zipOut.close();
    return buffer.toByteArray();
  } catch (IOException e) {
    // Should not happen as this is all in memory
    throw new RuntimeException("Unable to generate test zip!", e);
  }
}
 
Example 7
Source File: WriteableZip.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
public WriteableZip(File file) throws IOException {
    filePath = file.getAbsolutePath();
    files = new HashSet<String>();
    outputFile = new File(filePath + ".tmp");
    outputFileStream = new FileOutputStream(outputFile);
    output = new ZipOutputStream(outputFileStream);
    output.setMethod(ZipOutputStream.DEFLATED);
    output.setLevel(Deflater.NO_COMPRESSION);
    streamIsOpened = false;
}
 
Example 8
Source File: ZipOutputStreamTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.util.zip.ZipOutputStream#write(byte[], int, int)
 */
/* J2ObjC removed: not supported by Junit 4.11 (https://github.com/google/j2objc/issues/1318).
@DisableResourceLeakageDetection(
        why = "InflaterOutputStream.close() does not work properly if finish() throws an"
                + " exception; finish() throws an exception if the output is invalid; this is"
                + " an issue with the ZipOutputStream created in setUp()",
        bug = "31797037") */
public void test_write$BII_2() throws IOException {
    // Regression for HARMONY-577
    File f1 = File.createTempFile("testZip1", "tst");
    f1.deleteOnExit();
    FileOutputStream stream1 = new FileOutputStream(f1);
    ZipOutputStream zip1 = new ZipOutputStream(stream1);
    zip1.putNextEntry(new ZipEntry("one"));
    zip1.setMethod(ZipOutputStream.STORED);
    zip1.setMethod(ZipEntry.STORED);

    zip1.write(new byte[2]);

    try {
        zip1.putNextEntry(new ZipEntry("Second"));
        fail("ZipException expected");
    } catch (ZipException e) {
        // expected - We have not set an entry
    }

    try {
        zip1.write(new byte[2]); // try to write data without entry
        fail("expected IOE there");
    } catch (IOException e2) {
        // expected
    }

    zip1.close();
}
 
Example 9
Source File: ZipBytesProducer.java    From webery with MIT License 5 votes vote down vote up
public ZipBytesProducer(Iterator<Pair<ZipEntry, Lazy<InputStream>>> entries) {
    this.entries = entries;
    out = new DirectByteArrayOutputStream(buffer.length);
    zipout = new ZipOutputStream(out);
    zipout.setMethod(ZipOutputStream.DEFLATED);
    zipout.setLevel(0);
}
 
Example 10
Source File: SpringBootZipOnDemandInputStream.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
protected ZipOutputStream createOutputStream(final OutputStream outputStream) {
    ZipOutputStream stream = new ZipOutputStream(outputStream);
    stream.setMethod(ZipEntry.STORED);
    stream.setLevel(Deflater.NO_COMPRESSION);
    return stream;
}
 
Example 11
Source File: ChatServer.java    From aion-germany with GNU General Public License v3.0 4 votes vote down vote up
private static void initalizeLoggger() {
    new File("./log/backup/").mkdirs();
    File[] files = new File("log").listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".log");
        }
    });

    if (files != null && files.length > 0) {
        byte[] buf = new byte[1024];
        try {
            String outFilename = "./log/backup/" + new SimpleDateFormat("yyyy-MM-dd HHmmss").format(new Date()) + ".zip";
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
            out.setMethod(ZipOutputStream.DEFLATED);
            out.setLevel(Deflater.BEST_COMPRESSION);

            for (File logFile : files) {
                FileInputStream in = new FileInputStream(logFile);
                out.putNextEntry(new ZipEntry(logFile.getName()));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
                logFile.delete();
            }
            out.close();
        } catch (IOException e) {
        }
    }
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    try {
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(lc);
        lc.reset();
        configurator.doConfigure("config/slf4j-logback.xml");
    } catch (JoranException je) {
        throw new RuntimeException("Failed to configure loggers, shutting down...", je);
    }
}
 
Example 12
Source File: GameServer.java    From aion-germany with GNU General Public License v3.0 4 votes vote down vote up
private static void initalizeLoggger() {
	new File("./log/backup/").mkdirs();
	File[] files = new File("log").listFiles(new FilenameFilter() {

		@Override
		public boolean accept(File dir, String name) {
			return name.endsWith(".log");
		}
	});

	if (files != null && files.length > 0) {
		byte[] buf = new byte[1024];
		try {
			String outFilename = "./log/backup/" + new SimpleDateFormat("yyyy-MM-dd HHmmss").format(new Date()) + ".zip";
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
			out.setMethod(ZipOutputStream.DEFLATED);
			out.setLevel(Deflater.BEST_COMPRESSION);

			for (File logFile : files) {
				FileInputStream in = new FileInputStream(logFile);
				out.putNextEntry(new ZipEntry(logFile.getName()));
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				out.closeEntry();
				in.close();
				logFile.delete();
			}
			out.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
	try {
		JoranConfigurator configurator = new JoranConfigurator();
		configurator.setContext(lc);
		lc.reset();
		configurator.doConfigure("config/slf4j-logback.xml");
	}
	catch (JoranException je) {
		throw new RuntimeException("[LoggerFactory] Failed to configure loggers, shutting down...", je);
	}
}
 
Example 13
Source File: LoginServer.java    From aion-germany with GNU General Public License v3.0 4 votes vote down vote up
private static void initalizeLoggger() {
    new File("./log/backup/").mkdirs();
    File[] files = new File("log").listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".log");
        }
    });

    if (files != null && files.length > 0) {
        byte[] buf = new byte[1024];
        try {
            String outFilename = "./log/backup/" + new SimpleDateFormat("yyyy-MM-dd HHmmss").format(new Date()) + ".zip";
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
            out.setMethod(ZipOutputStream.DEFLATED);
            out.setLevel(Deflater.BEST_COMPRESSION);

            for (File logFile : files) {
                FileInputStream in = new FileInputStream(logFile);
                out.putNextEntry(new ZipEntry(logFile.getName()));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
                logFile.delete();
            }
            out.close();
        } catch (IOException e) {
        }
    }
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    try {
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(lc);
        lc.reset();
        configurator.doConfigure("config/slf4j-logback.xml");
    } catch (JoranException je) {
        throw new RuntimeException("Failed to configure loggers, shutting down...", je);
    }
}
 
Example 14
Source File: DownloadController.java    From airsonic with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Downloads the given files.  The files are packed together in an
 * uncompressed zip-file.
 *
 * @param response     The HTTP response.
 * @param status       The download status.
 * @param files        The files to download.
 * @param indexes      Only download songs at these indexes. May be <code>null</code>.
 * @param coverArtFile The cover art file to include, may be {@code null}.
 * @param range        The byte range, may be <code>null</code>.
 * @param zipFileName  The name of the resulting zip file.   @throws IOException If an I/O error occurs.
 */
private void downloadFiles(HttpServletResponse response, TransferStatus status, List<MediaFile> files, int[] indexes, File coverArtFile, HttpRange range, String zipFileName) throws IOException {
    boolean cover_embedded = false;

    if (indexes != null && indexes.length == 1) {
        downloadFile(response, status, files.get(indexes[0]).getFile(), range);
        return;
    }

    LOG.info("Starting to download '" + zipFileName + "' to " + status.getPlayer());
    response.setContentType("application/x-download");
    response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodeAsRFC5987(zipFileName));

    ZipOutputStream out = new ZipOutputStream(RangeOutputStream.wrap(response.getOutputStream(), range));
    out.setMethod(ZipOutputStream.STORED);  // No compression.

    Set<MediaFile> filesToDownload = new HashSet<>();
    if (indexes == null) {
        filesToDownload.addAll(files);
    } else {
        for (int index : indexes) {
            try {
                filesToDownload.add(files.get(index));
            } catch (IndexOutOfBoundsException x) { /* Ignored */}
        }
    }

    for (MediaFile mediaFile : filesToDownload) {
        zip(out, mediaFile.getParentFile(), mediaFile.getFile(), status, range);
        if (coverArtFile != null && coverArtFile.exists()) {
            if (mediaFile.getFile().getCanonicalPath().equals(coverArtFile.getCanonicalPath())) {
                cover_embedded = true;
            }
        }
    }
    if (coverArtFile != null && coverArtFile.exists() && !cover_embedded) {
        zip(out, coverArtFile.getParentFile(), coverArtFile, status, range);
    }


    out.close();
    LOG.info("Downloaded '" + zipFileName + "' to " + status.getPlayer());
}
 
Example 15
Source File: OpenOfficeOutputFilter.java    From tn5250j with GNU General Public License v2.0 3 votes vote down vote up
public void createFileInstance(String fileName) throws
                           FileNotFoundException {


   fout = new ZipOutputStream(new FileOutputStream(fileName));
   fout.setMethod(ZipOutputStream.DEFLATED);
   writeManifestEntry();

   // initialize work variables
   row = 0;
   sb = new StringBuffer();

}