Java Code Examples for org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream#closeArchiveEntry()

The following examples show how to use org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream#closeArchiveEntry() . 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: ZipUtil.java    From bbs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 添加目录到Zip
 * @param file
 * @param out
 * @param entryPath
 */
private static void addDirectoryToZip(File file, ZipArchiveOutputStream out, String entryPath) {
    
    try {
         
        String path=entryPath + file.getName();
        if(file.isDirectory()){
            path=formatDirPath(path); //为了在压缩文件中包含空文件夹
        }
        ZipArchiveEntry entry = new ZipArchiveEntry(path);
        entry.setTime(file.lastModified());
        // entry.setSize(files[i].length());
        out.putArchiveEntry(entry);

        out.closeArchiveEntry();
    } catch (IOException e) {
      //  e.printStackTrace();
    	if (logger.isErrorEnabled()) {
         logger.error("添加目录到Zip",e);
     }
    } finally {
       
    }
}
 
Example 2
Source File: Zipper.java    From james-project with Apache License 2.0 6 votes vote down vote up
private void storeInArchive(MessageResult message, ZipArchiveOutputStream archiveOutputStream) throws IOException {
    String entryId = message.getMessageId().serialize();
    ZipArchiveEntry archiveEntry = createMessageZipArchiveEntry(message, archiveOutputStream, entryId);

    archiveOutputStream.putArchiveEntry(archiveEntry);
    try {
        Content content = message.getFullContent();
        try (InputStream stream = content.getInputStream()) {
            IOUtils.copy(stream, archiveOutputStream);
        }
    } catch (MailboxException e) {
        LOGGER.error("Error while storing message in archive", e);
    }

    archiveOutputStream.closeArchiveEntry();
}
 
Example 3
Source File: Zipper.java    From james-project with Apache License 2.0 6 votes vote down vote up
private void storeInArchive(MailboxWithAnnotations mailboxWithAnnotations, ZipArchiveOutputStream archiveOutputStream) throws IOException {
    Mailbox mailbox = mailboxWithAnnotations.mailbox;
    List<MailboxAnnotation> annotations = mailboxWithAnnotations.annotations;

    String name = mailbox.getName();
    ZipArchiveEntry archiveEntry = (ZipArchiveEntry) archiveOutputStream.createArchiveEntry(new Directory(name), name);

    archiveEntry.addExtraField(EntryTypeExtraField.TYPE_MAILBOX);
    archiveEntry.addExtraField(new MailboxIdExtraField(mailbox.getMailboxId().serialize()));
    archiveEntry.addExtraField(new UidValidityExtraField(mailbox.getUidValidity().asLong()));

    archiveOutputStream.putArchiveEntry(archiveEntry);
    archiveOutputStream.closeArchiveEntry();

    storeAllAnnotationsInArchive(archiveOutputStream, annotations, name);
}
 
Example 4
Source File: EntityImportExport.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] exportEntitiesToZIP(Collection<? extends Entity> entities) {
    String json = entitySerialization.toJson(entities, null, EntitySerializationOption.COMPACT_REPEATED_ENTITIES);
    byte[] jsonBytes = json.getBytes(StandardCharsets.UTF_8);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(byteArrayOutputStream);
    zipOutputStream.setMethod(ZipArchiveOutputStream.STORED);
    zipOutputStream.setEncoding(StandardCharsets.UTF_8.name());
    ArchiveEntry singleDesignEntry = newStoredEntry("entities.json", jsonBytes);
    try {
        zipOutputStream.putArchiveEntry(singleDesignEntry);
        zipOutputStream.write(jsonBytes);
        zipOutputStream.closeArchiveEntry();
    } catch (Exception e) {
        throw new RuntimeException("Error on creating zip archive during entities export", e);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
    }
    return byteArrayOutputStream.toByteArray();
}
 
Example 5
Source File: FoldersServiceBean.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] exportFolder(Folder folder) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(byteArrayOutputStream);
    zipOutputStream.setMethod(ZipArchiveOutputStream.STORED);
    zipOutputStream.setEncoding(StandardCharsets.UTF_8.name());
    String xml = createXStream().toXML(folder);
    byte[] xmlBytes = xml.getBytes(StandardCharsets.UTF_8);
    ArchiveEntry zipEntryDesign = newStoredEntry("folder.xml", xmlBytes);
    zipOutputStream.putArchiveEntry(zipEntryDesign);
    zipOutputStream.write(xmlBytes);
    try {
        zipOutputStream.closeArchiveEntry();
    } catch (Exception ex) {
        throw new RuntimeException(String.format("Exception occurred while exporting folder %s.",  folder.getName()));
    }

    zipOutputStream.close();
    return byteArrayOutputStream.toByteArray();
}
 
Example 6
Source File: Assembler.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Adds the given file in the ZIP file. If the given file is a directory, then this method
 * recursively adds all files contained in this directory. This method is invoked for zipping
 * the "application/sis-console/src/main/artifact" directory and sub-directories before to zip.
 */
private void appendRecursively(final File file, String relativeFile, final ZipArchiveOutputStream out) throws IOException {
    if (file.isDirectory()) {
        relativeFile += '/';
    }
    final ZipArchiveEntry entry = new ZipArchiveEntry(file, relativeFile);
    if (file.canExecute()) {
        entry.setUnixMode(0744);
    }
    out.putArchiveEntry(entry);
    if (!entry.isDirectory()) {
        try (FileInputStream in = new FileInputStream(file)) {
            in.transferTo(out);
        }
    }
    out.closeArchiveEntry();
    if (entry.isDirectory()) {
        for (final String filename : file.list(this)) {
            appendRecursively(new File(file, filename), relativeFile.concat(filename), out);
        }
    }
}
 
Example 7
Source File: ArchiveUtils.java    From support-diagnostics with Apache License 2.0 5 votes vote down vote up
public static void archiveResultsZip(String archiveFilename, ZipArchiveOutputStream taos, File file, String path, boolean append) {
   String relPath = "";

   try {
      if (append) {
         relPath = path + "/" + file.getName() + "-" + archiveFilename;
      } else {
         relPath = path + "/" + file.getName();
      }
      ZipArchiveEntry tae = new ZipArchiveEntry(file, relPath);
      taos.putArchiveEntry(tae);

      if (file.isFile()) {
         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
         IOUtils.copy(bis, taos);
         taos.closeArchiveEntry();
         bis.close();

      } else if (file.isDirectory()) {
         taos.closeArchiveEntry();
         for (File childFile : file.listFiles()) {
            archiveResultsZip(archiveFilename, taos, childFile, relPath, false);
         }
      }
   } catch (IOException e) {
      logger.error(Constants.CONSOLE,"Archive Error", e);
   }
}
 
Example 8
Source File: Zipper.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void storeInArchive(MailboxAnnotation annotation, String directory, ZipArchiveOutputStream archiveOutputStream) throws IOException {
    String entryId = directory + "/" + annotation.getKey().asString();
    ZipArchiveEntry archiveEntry = (ZipArchiveEntry) archiveOutputStream.createArchiveEntry(new File(entryId), entryId);
    archiveEntry.addExtraField(EntryTypeExtraField.TYPE_MAILBOX_ANNOTATION);
    archiveOutputStream.putArchiveEntry(archiveEntry);

    annotation.getValue().ifPresent(value -> {
        try (PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(archiveOutputStream, Charsets.UTF_8), AUTO_FLUSH)) {
            printWriter.print(value);
        }
    });

    archiveOutputStream.closeArchiveEntry();
}
 
Example 9
Source File: Zipper.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void storeAllAnnotationsInArchive(ZipArchiveOutputStream archiveOutputStream, List<MailboxAnnotation> annotations, String name) throws IOException {
    if (!annotations.isEmpty()) {
        String annotationsDirectoryPath = name + "/" + ANNOTATION_DIRECTORY;
        ZipArchiveEntry annotationDirectory = (ZipArchiveEntry) archiveOutputStream.createArchiveEntry(
            new Directory(annotationsDirectoryPath), annotationsDirectoryPath);
        annotationDirectory.addExtraField(EntryTypeExtraField.TYPE_MAILBOX_ANNOTATION_DIR);
        archiveOutputStream.putArchiveEntry(annotationDirectory);
        archiveOutputStream.closeArchiveEntry();
        annotations.forEach(Throwing.consumer(annotation ->
            storeInArchive(annotation, annotationsDirectoryPath, archiveOutputStream)));
    }
}
 
Example 10
Source File: DeletedMessageZipper.java    From james-project with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void putMessageToEntry(ZipArchiveOutputStream zipOutputStream, DeletedMessage message, Optional<InputStream> maybeContent) throws IOException {
    if (maybeContent.isPresent()) {
        try (InputStream closableMessageContent = maybeContent.get()) {
            zipOutputStream.putArchiveEntry(createEntry(zipOutputStream, message));
            IOUtils.copy(closableMessageContent, zipOutputStream);
            zipOutputStream.closeArchiveEntry();
        }
    }
}
 
Example 11
Source File: LogArchiver.java    From cuba with Apache License 2.0 5 votes vote down vote up
public static void writeArchivedLogToStream(File logFile, OutputStream outputStream) throws IOException {
    if (!logFile.exists()) {
        throw new FileNotFoundException();
    }

    File tempFile = File.createTempFile(FilenameUtils.getBaseName(logFile.getName()) + "_log_", ".zip");

    ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(tempFile);
    zipOutputStream.setMethod(ZipArchiveOutputStream.DEFLATED);
    zipOutputStream.setEncoding(ZIP_ENCODING);

    ArchiveEntry archiveEntry = newArchive(logFile);
    zipOutputStream.putArchiveEntry(archiveEntry);

    FileInputStream logFileInput = new FileInputStream(logFile);
    IOUtils.copyLarge(logFileInput, zipOutputStream);

    logFileInput.close();

    zipOutputStream.closeArchiveEntry();
    zipOutputStream.close();

    FileInputStream tempFileInput = new FileInputStream(tempFile);
    IOUtils.copyLarge(tempFileInput, outputStream);

    tempFileInput.close();

    FileUtils.deleteQuietly(tempFile);
}
 
Example 12
Source File: ArchiveUtils.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Recursively create ZIP archive from directory
 */
public static void createZip(File path, String root, OutputStream os) throws IOException {
	log.debug("createZip({}, {}, {})", new Object[]{path, root, os});

	if (path.exists() && path.canRead()) {
		ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(os);
		zaos.setComment("Generated by OpenKM");
		zaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
		zaos.setUseLanguageEncodingFlag(true);
		zaos.setFallbackToUTF8(true);
		zaos.setEncoding("UTF-8");

		// Prevents java.util.zip.ZipException: ZIP file must have at least one entry
		ZipArchiveEntry zae = new ZipArchiveEntry(root + "/");
		zaos.putArchiveEntry(zae);
		zaos.closeArchiveEntry();

		createZipHelper(path, zaos, root);

		zaos.flush();
		zaos.finish();
		zaos.close();
	} else {
		throw new IOException("Can't access " + path);
	}

	log.debug("createZip: void");
}
 
Example 13
Source File: ArchiveUtils.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create ZIP archive from file
 */
public static void createZip(File path, OutputStream os) throws IOException {
	log.debug("createZip({}, {})", new Object[]{path, os});

	if (path.exists() && path.canRead()) {
		ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(os);
		zaos.setComment("Generated by OpenKM");
		zaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
		zaos.setUseLanguageEncodingFlag(true);
		zaos.setFallbackToUTF8(true);
		zaos.setEncoding("UTF-8");

		log.debug("FILE {}", path);
		ZipArchiveEntry zae = new ZipArchiveEntry(path.getName());
		zaos.putArchiveEntry(zae);
		FileInputStream fis = new FileInputStream(path);
		IOUtils.copy(fis, zaos);
		fis.close();
		zaos.closeArchiveEntry();

		zaos.flush();
		zaos.finish();
		zaos.close();
	} else {
		throw new IOException("Can't access " + path);
	}

	log.debug("createZip: void");
}
 
Example 14
Source File: CompressExample.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
public static void makeZip() throws IOException, ArchiveException{
		File f1 = new File("D:/compresstest.txt");
        File f2 = new File("D:/test1.xml");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        //ArchiveOutputStream ostemp = new ArchiveStreamFactory().createArchiveOutputStream("zip", baos);
        ZipArchiveOutputStream ostemp = new ZipArchiveOutputStream(baos);
        ostemp.setEncoding("GBK");
        ostemp.putArchiveEntry(new ZipArchiveEntry(f1.getName()));
        IOUtils.copy(new FileInputStream(f1), ostemp);
        ostemp.closeArchiveEntry();
        ostemp.putArchiveEntry(new ZipArchiveEntry(f2.getName()));
        IOUtils.copy(new FileInputStream(f2), ostemp);
        ostemp.closeArchiveEntry();
        ostemp.finish();
        ostemp.close();

//      final OutputStream out = new FileOutputStream("D:/testcompress.zip");
        final OutputStream out = new FileOutputStream("D:/中文名字.zip");
        ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
        os.putArchiveEntry(new ZipArchiveEntry("打包.zip"));
        baos.writeTo(os);
        os.closeArchiveEntry();
        baos.close();
        os.finish();
        os.close();
	}
 
Example 15
Source File: MCRZipServlet.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void sendMetadataCompressed(String fileName, byte[] content, long lastModified,
    ZipArchiveOutputStream container) throws IOException {
    ZipArchiveEntry entry = new ZipArchiveEntry(fileName);
    entry.setSize(content.length);
    entry.setTime(lastModified);
    container.putArchiveEntry(entry);
    container.write(content);
    container.closeArchiveEntry();
}
 
Example 16
Source File: MCRZipServlet.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void sendCompressedFile(MCRPath file, BasicFileAttributes attrs, ZipArchiveOutputStream container)
    throws IOException {
    ZipArchiveEntry entry = new ZipArchiveEntry(getFilename(file));
    entry.setTime(attrs.lastModifiedTime().toMillis());
    entry.setSize(attrs.size());
    container.putArchiveEntry(entry);
    try {
        Files.copy(file, container);
    } finally {
        container.closeArchiveEntry();
    }
}
 
Example 17
Source File: MCRZipServlet.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void sendCompressedDirectory(MCRPath file, BasicFileAttributes attrs, ZipArchiveOutputStream container)
    throws IOException {
    ZipArchiveEntry entry = new ZipArchiveEntry(getFilename(file) + "/");
    entry.setTime(attrs.lastModifiedTime().toMillis());
    container.putArchiveEntry(entry);
    container.closeArchiveEntry();
}
 
Example 18
Source File: FunctionZipProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void addZipEntry(ZipArchiveOutputStream zip, Path path, String name, int mode) throws Exception {
    ZipArchiveEntry entry = (ZipArchiveEntry) zip.createArchiveEntry(path.toFile(), name);
    entry.setUnixMode(mode);
    zip.putArchiveEntry(entry);
    try (InputStream i = Files.newInputStream(path)) {
        IOUtils.copy(i, zip);
    }
    zip.closeArchiveEntry();
}
 
Example 19
Source File: ZipUtil.java    From bbs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 添加文件到Zip
 * @param file
 * @param out
 * @param entryPath
 */
private static void addFileToZip(File file, ZipArchiveOutputStream out, String entryPath) {
    InputStream ins = null;
    try {
         
        String path=entryPath + file.getName();
        if(file.isDirectory()){
            path=formatDirPath(path); //为了在压缩文件中包含空文件夹
        }
        ZipArchiveEntry entry = new ZipArchiveEntry(path);
        entry.setTime(file.lastModified());
        // entry.setSize(files[i].length());
        out.putArchiveEntry(entry);
        if(!file.isDirectory()){
            ins = new BufferedInputStream(new FileInputStream(file.getAbsolutePath()));
            IOUtils.copy(ins, out);
        }
        out.closeArchiveEntry();
    } catch (IOException e) {
      //  e.printStackTrace();
    	if (logger.isErrorEnabled()) {
         logger.error("添加文件到Zip",e);
     }
    } finally {
        IOUtils.closeQuietly(ins);
    }
}
 
Example 20
Source File: FunctionZipProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void copyZipEntry(ZipArchiveOutputStream zip, InputStream zinput, ZipArchiveEntry from) throws Exception {
    ZipArchiveEntry entry = new ZipArchiveEntry(from);
    zip.putArchiveEntry(entry);
    IOUtils.copy(zinput, zip);
    zip.closeArchiveEntry();
}