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.taobao.android.builder.tools.zip.ZipUtils.java

public static void rezip(File output, File srcDir, Map<String, ZipEntry> zipEntryMethodMap) throws Exception {
    if (output.isDirectory()) {
        throw new IOException("This is a directory!");
    }// w  w  w.  j av a  2s  .  co m
    if (!output.getParentFile().exists()) {
        output.getParentFile().mkdirs();
    }

    if (!output.exists()) {
        output.createNewFile();
    }
    List fileList = getSubFiles(srcDir);
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(output));
    ZipEntry ze = null;
    byte[] buf = new byte[1024];
    int readLen = 0;
    for (int i = 0; i < fileList.size(); i++) {
        File f = (File) fileList.get(i);
        ze = new ZipEntry(getAbsFileName(srcDir.getPath(), f));
        ze.setSize(f.length());
        ze.setTime(f.lastModified());
        if (zipEntryMethodMap != null) {
            ZipEntry originEntry = zipEntryMethodMap.get(ze.getName());
            if (originEntry != null) {
                if (originEntry.getMethod() == STORED) {
                    ze.setCompressedSize(f.length());
                    InputStream in = new BufferedInputStream(new FileInputStream(f));
                    try {
                        CRC32 crc = new CRC32();
                        int c;
                        while ((c = in.read()) != -1) {
                            crc.update(c);
                        }
                        ze.setCrc(crc.getValue());
                    } finally {
                        in.close();
                    }
                }
                ze.setMethod(originEntry.getMethod());
            }
        }
        zos.putNextEntry(ze);
        InputStream is = new BufferedInputStream(new FileInputStream(f));
        while ((readLen = is.read(buf, 0, 1024)) != -1) {
            zos.write(buf, 0, readLen);
        }
        is.close();
    }
    zos.close();
}

From source file:com.ephesoft.dcma.util.FileUtils.java

/**
 * This method zips the contents of Directory specified into a zip file whose name is provided.
 * //from www.  j a  v a 2  s.  c om
 * @param dir2zip {@link String}
 * @param zout {@link String}
 * @param dir2zipName {@link String}
 * @throws IOException in case of error
 */
public static void zipDirectory(String dir2zip, ZipOutputStream zout, String dir2zipName) throws IOException {
    File srcDir = new File(dir2zip);
    List<String> fileList = listDirectory(srcDir);
    for (String fileName : fileList) {
        File file = new File(srcDir.getParent(), fileName);
        String zipName = fileName;
        if (File.separatorChar != FORWARD_SLASH) {
            zipName = fileName.replace(File.separatorChar, FORWARD_SLASH);
        }
        zipName = zipName.substring(
                zipName.indexOf(dir2zipName + BACKWARD_SLASH) + 1 + (dir2zipName + BACKWARD_SLASH).length());

        ZipEntry zipEntry;
        if (file.isFile()) {
            zipEntry = new ZipEntry(zipName);
            zipEntry.setTime(file.lastModified());
            zout.putNextEntry(zipEntry);
            FileInputStream fin = new FileInputStream(file);
            byte[] buffer = new byte[UtilConstants.BUFFER_CONST];
            for (int n; (n = fin.read(buffer)) > 0;) {
                zout.write(buffer, 0, n);
            }
            if (fin != null) {
                fin.close();
            }
        } else {
            zipEntry = new ZipEntry(zipName + FORWARD_SLASH);
            zipEntry.setTime(file.lastModified());
            zout.putNextEntry(zipEntry);
        }
    }
    if (zout != null) {
        zout.close();
    }
}

From source file:com.wegas.core.jcr.content.ContentConnector.java

/**
 * Compress directory and children to ZipOutputStream. Warning: metadatas
 * are not included due to zip limitation
 *
 * @param out  a ZipOutputStream to write files to
 * @param path root path to compress//from   www. j a  v  a 2s  .  com
 * @throws RepositoryException
 * @throws IOException
 */
public void zipDirectory(ZipOutputStream out, String path) throws RepositoryException, IOException {
    AbstractContentDescriptor node = DescriptorFactory.getDescriptor(path, this);
    DirectoryDescriptor root;
    if (node.isDirectory()) {
        root = (DirectoryDescriptor) node;
    } else {
        return;
    }
    List<AbstractContentDescriptor> list = root.list();

    ZipEntry entry;
    for (AbstractContentDescriptor item : list) {
        entry = item.getZipEntry();
        try {
            out.putNextEntry(entry);
        } catch (ZipException ex) {
            logger.warn("error");
        }
        if (item.isDirectory()) {
            zipDirectory(out, item.getFullPath());
        } else {
            byte[] write = ((FileDescriptor) item).getBytesData();
            out.write(write, 0, write.length);
        }
    }
    out.closeEntry();
}

From source file:au.org.ala.bhl.service.DocumentCacheService.java

public void compressPages(ItemDescriptor itemDesc) {
    File itemDir = new File(getItemDirectoryPath(itemDesc.getInternetArchiveId()));
    File file = getPageArchiveFile(itemDesc);
    if (file.exists()) {
        log("Deleting existing archive file: %s", file.getAbsolutePath());
        file.delete();/*  w  ww . j a  v  a 2s . co  m*/
    }
    try {
        File[] candidates = itemDir.listFiles();
        int pageCount = 0;

        ZipOutputStream out = null;

        for (File candidate : candidates) {
            Matcher m = PAGE_FILE_REGEX.matcher(candidate.getName());
            if (m.matches()) {
                if (out == null) {
                    out = new ZipOutputStream(new FileOutputStream(file));
                }
                pageCount++;
                FileInputStream in = new FileInputStream(candidate);
                out.putNextEntry(new ZipEntry(candidate.getName()));
                byte[] buf = new byte[2048];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();

                candidate.delete();
            }
        }

        if (out != null) {
            out.close();
            log("%d pages add to pages.zip for item %s", pageCount, itemDesc);
        } else {
            log("No pages for item %s", itemDesc);
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.webpagebytes.cms.controllers.FlatStorageImporterExporter.java

protected void exportLocales(ZipOutputStream zos, String path) throws WPBIOException {
    try {//  w w w .ja  v a  2s  .com
        WPBProject project = dataStorage.get(WPBProject.PROJECT_KEY, WPBProject.class);
        Map<String, Object> map = new HashMap<String, Object>();
        exporter.export(project, map);
        String metadataXml = path + "metadata.xml";
        ZipEntry metadataZe = new ZipEntry(metadataXml);
        zos.putNextEntry(metadataZe);
        exportToXMLFormat(map, zos);
        zos.closeEntry();

    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new WPBIOException("Cannot export uri's to Zip", e);
    }
}

From source file:com.flexive.core.storage.GenericDivisionExporter.java

/**
 * Start a new zip entry/file// w  ww  .ja  va2 s  .  c  om
 *
 * @param out   zip output stream to use
 * @param entry name of the new entry
 * @throws IOException on errors
 */
private void startEntry(ZipOutputStream out, String entry) throws IOException {
    ZipEntry ze = new ZipEntry(entry);
    out.putNextEntry(ze);
    writeHeader(out);
}

From source file:net.sourceforge.jweb.maven.mojo.PropertiesOverideMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (disabled) {
        this.getLog().info("plugin was disabled");
        return;//from  ww  w .  j a v a2 s.com
    }
    processConfiguration();
    if (replacements.isEmpty()) {
        this.getLog().info("Nothing to replace with");
        return;
    }

    String name = this.builddir.getAbsolutePath() + File.separator + this.finalName + "." + this.packing;//the final package
    this.getLog().debug("final artifact: " + name);// the final package

    try {
        File finalWarFile = new File(name);
        File tempFile = File.createTempFile(finalWarFile.getName(), null);
        tempFile.delete();//check deletion
        boolean renameOk = finalWarFile.renameTo(tempFile);
        if (!renameOk) {
            getLog().error("Can not rename file, please check.");
            return;
        }

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile));
        ZipFile zipFile = new ZipFile(tempFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (acceptMime(entry)) {
                getLog().info("applying replacements for " + entry.getName());
                InputStream inputStream = zipFile.getInputStream(entry);
                String src = IOUtils.toString(inputStream, encoding);
                //do replacement
                for (Entry<String, String> e : replacements.entrySet()) {
                    src = src.replaceAll("#\\{" + e.getKey() + "}", e.getValue());
                }
                out.putNextEntry(new ZipEntry(entry.getName()));
                IOUtils.write(src, out, encoding);
                inputStream.close();
            } else {
                //not repalce, just put entry back to out zip
                out.putNextEntry(entry);
                InputStream inputStream = zipFile.getInputStream(entry);
                byte[] buf = new byte[512];
                int len = -1;
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                inputStream.close();
                continue;
            }
        }
        zipFile.close();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

public void dumpTouchOsc(TOP top, String destDirname, String destFilename) {

    reverseZOrders(top);//from w w  w.  j a  va2 s.  co  m
    //
    // Get tests for TouchOSC legacy compliances : need precise version info
    //
    //applyBase64Transformation(top);

    // Create a resource set.
    //
    ResourceSet resourceSet = new ResourceSetImpl();

    //
    // Register the default resource factory -- only needed for stand-alone!
    //
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(TouchoscPackage.eNS_PREFIX,
            new TouchoscResourceFactoryImpl());
    resourceSet.getPackageRegistry().put(TouchoscPackage.eNS_URI, TouchoscPackage.eINSTANCE);
    resourceSet.getPackageRegistry().put(TouchoscappPackage.eNS_URI, TouchoscappPackage.eINSTANCE);

    String dirname;
    if (destDirname == null) {
        dirname = Platform.getInstanceLocation().getURL().getPath() + "/" + UUID.randomUUID().toString();

        if (Platform.inDebugMode()) {
            System.out.println("creating " + dirname + " directory");
        }

        new File(dirname).mkdir();
    } else {
        dirname = destDirname;
    }

    //
    // Get the URI of the model file.
    //
    URI touchoscURI = URI.createFileURI(dirname + "/" + "index.xml");

    //
    // Demand load the resource for this file.
    //
    Resource resource = resourceSet.createResource(touchoscURI);

    resource.getContents().add(top);

    try {
        Map<Object, Object> options = new HashMap<Object, Object>();
        options.put(XMLResource.OPTION_ENCODING, "UTF-8");
        resource.save(options);
    } catch (IOException e) {
        e.printStackTrace();
    }

    String TOUCHOSC_HEADER = "<touchosc:TOP xmi:version=\"2.0\" xmlns:xmi=\"http://www.omg.org/XMI\" xmlns:touchosc=\"http:///net.sf.smbt.touchosc/src/net/sf/smbt/touchosc/model/touchosc.xsd\">";
    String TOUCHOSC_FOOTER = "</touchosc:TOP>";

    String path = touchoscURI.path().toString();
    String outputZipFile = dirname + "/" + destFilename + ".touchosc";

    try {
        FileInputStream touchoscFile = new FileInputStream(path);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(touchoscFile, Charset.forName("ASCII")));
        CharBuffer charBuffer = CharBuffer.allocate(65535);
        while (reader.read(charBuffer) != -1)

            charBuffer.flip();

        String content = charBuffer.toString();
        content = content.replace(TOUCHOSC_HEADER, "<touchosc>");
        content = content.replace(TOUCHOSC_FOOTER, "</touchosc>");
        content = content.replace("<layout>", "<layout version=\"10\" mode=\"" + top.getLayout().getMode()
                + "\" orientation=\"" + top.getLayout().getOrientation() + "\">");
        content = content.replace("numberX=", "number_x=");
        content = content.replace("numberY=", "number_y=");
        content = content.replace("invertedX=", "inverted_x=");
        content = content.replace("invertedY=", "inverted_y=");
        content = content.replace("localOff=", "local_off=");
        content = content.replace("oscCs=", "osc_cs=");
        content = content.replace("xypad", "xy");

        touchoscFile.close();

        FileOutputStream os = new FileOutputStream(path);

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, Charset.forName("UTF-8")));

        writer.write(content);
        writer.flush();

        os.flush();
        os.close();

        FileOutputStream fos = new FileOutputStream(outputZipFile);
        ZipOutputStream fileOS = new ZipOutputStream(fos);

        ZipEntry ze = new ZipEntry("index.xml");
        fileOS.putNextEntry(ze);
        fileOS.write(content.getBytes(Charset.forName("UTF-8")));
        fileOS.flush();
        fileOS.close();
        fos.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        File f = new File(path);
        if (f.exists() && f.canWrite()) {
            if (!f.delete()) {
                throw new IllegalArgumentException(path + " deletion failed");
            }
        }
    }
}

From source file:au.com.gaiaresources.bdrs.controller.theme.ThemeControllerTest.java

private byte[] createZip(Map<String, byte[]> files) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ZipOutputStream zipfile = new ZipOutputStream(bos);

    ZipEntry zipentry;/*from  ww w  .jav a 2  s. c  o  m*/
    for (Map.Entry<String, byte[]> entry : files.entrySet()) {
        zipentry = new ZipEntry(entry.getKey());
        zipfile.putNextEntry(zipentry);
        zipfile.write(entry.getValue());
    }

    zipfile.flush();
    zipfile.close();

    byte[] data = bos.toByteArray();
    bos.close();
    return data;
}

From source file:com.esofthead.mycollab.vaadin.resources.StreamDownloadResourceSupportExtDrive.java

private void zipResource(ZipOutputStream zipOutputStream, Collection<Resource> lstRes) {
    try {//from w w  w  .j  a  v  a2s .  com
        List<Resource> recurrResources;
        for (Resource currentResource : lstRes) {
            if (currentResource instanceof Folder) {
                if (!currentResource.isExternalResource()) {
                    recurrResources = resourceService.getResources(currentResource.getPath());
                } else {
                    ExternalResourceService service = ResourceUtils
                            .getExternalResourceService(ResourceUtils.getType(currentResource));
                    recurrResources = service.getResources(ResourceUtils.getExternalDrive(currentResource),
                            currentResource.getPath());
                }

                if (CollectionUtils.isEmpty(recurrResources)) {
                    zipOutputStream.putNextEntry(new ZipEntry(currentResource.getName() + "/"));
                } else {
                    for (Resource res : recurrResources) {
                        if (res instanceof Content) {
                            addFileToZip(currentResource.getName(), (Content) res, zipOutputStream);
                        } else if (res instanceof Folder) {
                            addFolderToZip(currentResource.getName(), res, zipOutputStream);
                        }
                    }
                }
            } else {
                addFileToZip("", (Content) currentResource, zipOutputStream);
            }
        }
    } catch (Exception e) {
        LOG.error("Error while save content", e);
    }
}