下面列出了java.util.zip.ZipOutputStream#finish ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Creates a ZIP file and returns the bytes for a given mapping of file name to file content.
*
* @param files the file map from name to content.
* @return the bytes of a ZIP file
* @throws IOException when creating the zip file fails at any point.
*/
public static byte[] zipFiles(Map<String, byte[]> files) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ZipOutputStream zos = new ZipOutputStream(baos);
for (String fileName : files.keySet()) {
final ZipEntry e = new ZipEntry(fileName);
try {
zos.putNextEntry(e);
zos.write(files.get(fileName));
zos.closeEntry();
} catch (Exception entryException) {
logger.error("Failed to add file to ZIP file.", entryException);
}
}
zos.finish();
zos.close();
final byte[] bytes = baos.toByteArray();
baos.close();
return bytes;
}
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
/**
*
*/
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();
}
public void doExport(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
IFileStore source = NewFileServlet.getFileStore(req, sourcePath);
if (req.getParameter(ProtocolConstants.PARAM_EXCLUDE) != null) {
excludedFiles = Arrays.asList(req.getParameter(ProtocolConstants.PARAM_EXCLUDE).split(","));
}
try {
if (source.fetchInfo(EFS.NONE, null).isDirectory() && source.childNames(EFS.NONE, null).length == 0) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "You cannot export an empty folder");
return;
}
resp.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
ZipOutputStream zout = new ZipOutputStream(resp.getOutputStream());
write(source, Path.EMPTY, zout);
zout.finish();
} catch (CoreException e) {
//we can't return an error response at this point because the output stream has been used
throw new ServletException(e);
}
}
/**
* Compress a text file using the ZIP compressing algorithm.
*
* @param filename the path to the file to be compressed
*/
public static void zipCompress(String filename) throws IOException {
FileOutputStream fos = new FileOutputStream(filename + COMPRESSION_SUFFIX);
CheckedOutputStream csum = new CheckedOutputStream(fos, new CRC32());
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(csum));
out.setComment("Failmon records.");
BufferedReader in = new BufferedReader(new FileReader(filename));
out.putNextEntry(new ZipEntry(new File(filename).getName()));
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.finish();
out.close();
}
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
@Override
public void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
throws BleachException {
ZipInputStream zipIn = new ZipInputStream(inputStream);
ZipOutputStream zipOut = new ZipOutputStream(outputStream);
try {
ZipEntry entry;
while ((entry = zipIn.getNextEntry()) != null) {
if (entry.isDirectory()) {
LOGGER.trace("Directory: {}", entry.getName());
ZipEntry newEntry = new ZipEntry(entry);
zipOut.putNextEntry(newEntry);
} else {
LOGGER.trace("Entry: {}", entry.getName());
sanitizeFile(session, zipIn, zipOut, entry);
}
zipOut.closeEntry();
}
zipOut.finish();
} catch (IOException e) {
LOGGER.error("Error in ArchiveBleach", e);
}
}
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
public static void main(String[] args) throws Exception {
URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
int len = conn.getContentLength();
byte[] data = new byte[len];
InputStream is = conn.getInputStream();
is.read(data);
is.close();
conn.setDefaultUseCaches(false);
File jar = File.createTempFile("B7050028", ".jar");
jar.deleteOnExit();
OutputStream os = new FileOutputStream(jar);
ZipOutputStream zos = new ZipOutputStream(os);
ZipEntry ze = new ZipEntry("B7050028.class");
ze.setMethod(ZipEntry.STORED);
ze.setSize(len);
CRC32 crc = new CRC32();
crc.update(data);
ze.setCrc(crc.getValue());
zos.putNextEntry(ze);
zos.write(data, 0, len);
zos.closeEntry();
zos.finish();
zos.close();
os.close();
System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
/**
* Zips an entire directory specified by the path.
*
* @param sourceDirectory the directory to read from. This directory and all subdirectories will
* be added to the zip-file. The path within the zip file is relative to the directory given
* as parameter, not absolute.
* @param outputStream the stream to write the zip-file to. This method does not close
* outputStream.
* @throws IOException the zipping failed, e.g. because the input was not readable.
*/
public static void zipDirectory(File sourceDirectory, OutputStream outputStream)
throws IOException {
checkNotNull(sourceDirectory);
checkNotNull(outputStream);
checkArgument(
sourceDirectory.isDirectory(),
"%s is not a valid directory",
sourceDirectory.getAbsolutePath());
ZipOutputStream zos = new ZipOutputStream(outputStream);
for (File file : sourceDirectory.listFiles()) {
zipDirectoryInternal(file, "", zos);
}
zos.finish();
}
@Override
public void exportAll ( final OutputStream stream ) throws IOException
{
final ZipOutputStream zos = new ZipOutputStream ( stream );
initExportFile ( zos );
final Collection<? extends ChannelId> ids = this.channelService.list ();
// TODO: run exportAll inside a channel service lock
for ( final ChannelId channelId : ids )
{
zos.putNextEntry ( new ZipEntry ( String.format ( "%s.zip", channelId.getId () ) ) );
exportChannel ( By.id ( channelId.getId () ), zos );
zos.closeEntry ();
}
zos.finish ();
}
/**
* Compress a text file using the ZIP compressing algorithm.
*
* @param filename the path to the file to be compressed
*/
public static void zipCompress(String filename) throws IOException {
FileOutputStream fos = new FileOutputStream(filename + COMPRESSION_SUFFIX);
CheckedOutputStream csum = new CheckedOutputStream(fos, new CRC32());
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(csum));
out.setComment("Failmon records.");
BufferedReader in = new BufferedReader(new FileReader(filename));
out.putNextEntry(new ZipEntry(new File(filename).getName()));
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.finish();
out.close();
}
@Override
public void close() throws IOException {
ZipOutputStream zos = (ZipOutputStream) delegate;
zos.flush();
zos.closeEntry();
zos.finish();
zos.close();
}
/**
* Finishes writing the contents of the ZIP output stream without closing the underlying stream.
*
* @param out the ZipOutputStream.
*/
public static void finishZipEntry( ZipOutputStream out )
{
try
{
out.finish();
}
catch ( Exception ex )
{
throw new RuntimeException( "Failed to finish the content of the ZipOutputStream", ex );
}
}
public void write ( final OutputStream stream ) throws IOException
{
if ( this.compressed )
{
final ZipOutputStream zos = new ZipOutputStream ( stream );
zos.putNextEntry ( new ZipEntry ( this.basename + ".xml" ) );
writeAll ( zos );
zos.closeEntry ();
zos.finish ();
}
else
{
writeAll ( stream );
}
}
public static void zip(File sourceDir, OutputStream targetStream) throws IOException {
if (!sourceDir.isFile() && !sourceDir.isDirectory()) {
return;
}
final ZipOutputStream cpZipOutputStream = new ZipOutputStream(targetStream);
cpZipOutputStream.setLevel(9);
zipFiles(sourceDir, sourceDir, cpZipOutputStream);
cpZipOutputStream.finish();
cpZipOutputStream.close();
}
/**
* Process the given input datasets and create a Zip archive on the
* given output file or dataset.
*/
public int run() throws IOException {
ZipOutputStream zipOutStream = openZipOutputStream();
try {
processInputFiles(zipOutStream);
zipOutStream.finish();
System.out.println(" done: " + errors + " errors");
return errors;
} finally {
try {
zipOutStream.close();
} catch (Throwable ignore) {}
}
}
/**
* Writes the given repository as ZIP-File into the given output stream.
*
* @param outputStream the output stream that should receive the zipfile.
* @param repository the repository that should be written.
* @throws IOException if an IO error prevents the writing of the file.
* @throws ContentIOException if a repository related IO error occurs.
*/
public static void writeAsZip( final OutputStream outputStream,
final Repository repository ) throws IOException, ContentIOException {
final ZipOutputStream zipout = new ZipOutputStream( outputStream );
writeToZipStream( zipout, repository );
zipout.finish();
zipout.flush();
}