Example usage for java.util.zip ZipOutputStream write

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

Introduction

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

Prototype

public synchronized void write(byte[] b, int off, int len) throws IOException 

Source Link

Document

Writes an array of bytes to the current ZIP entry data.

Usage

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String AddFilesToZip(ZipOutputStream out, String baseDir, String relDir) {
    final int BUFFER = 2048;
    String sRet = "";
    String curDir = "";
    String relFN = "";
    BufferedInputStream origin = null;
    byte data[] = new byte[BUFFER];

    if (relDir.length() > 0)
        curDir = baseDir + "/" + relDir;
    else/*ww w .  j a  v  a 2 s.c o m*/
        curDir = baseDir;

    File f = new File(curDir);

    if (f.isFile()) {
        try {
            relFN = ((relDir.length() > 0) ? relDir + "/" + f.getName() : f.getName());
            System.out.println("Adding: " + relFN);
            sRet += "Adding: " + relFN + lineSep;
            FileInputStream fi = new FileInputStream(curDir);
            origin = new BufferedInputStream(fi, BUFFER);
            ZipEntry entry = new ZipEntry(relFN);
            out.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return (sRet);
    }

    String files[] = f.list();

    if (files != null) {
        try {
            for (int i = 0; i < files.length; i++) {
                f = new File(curDir + "/" + files[i]);
                if (f.isDirectory()) {
                    if (relDir.length() > 0)
                        sRet += AddFilesToZip(out, baseDir, relDir + "/" + files[i]);
                    else
                        sRet += AddFilesToZip(out, baseDir, files[i]);
                } else {
                    relFN = ((relDir.length() > 0) ? relDir + "/" + files[i] : files[i]);
                    System.out.println("Adding: " + relFN);
                    sRet += "Adding: " + relFN + lineSep;
                    FileInputStream fi = new FileInputStream(curDir + "/" + files[i]);
                    origin = new BufferedInputStream(fi, BUFFER);
                    ZipEntry entry = new ZipEntry(relFN);
                    out.putNextEntry(entry);
                    int count;
                    while ((count = origin.read(data, 0, BUFFER)) != -1) {
                        out.write(data, 0, count);
                    }
                    origin.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return (sRet);
}

From source file:org.exoplatform.faq.service.impl.JCRDataStorage.java

@Override
public InputStream exportData(String categoryId, boolean createZipFile) throws Exception {
    Node categoryNode = getCategoryNodeById(categoryId);
    Session session = categoryNode.getSession();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    File file = null;/*from  www .j  a  v  a  2  s . c  om*/
    List<File> listFiles = new ArrayList<File>();
    session.exportSystemView(categoryNode.getPath(), bos, false, false);
    listFiles.add(CommonUtils.getXMLFile(bos, "eXo Knowledge Suite - Answers", "Category",
            CommonUtils.getGreenwichMeanTime().getTime(), categoryNode.getName()));
    ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream("exportCategory.zip"));
    try {
        int byteReads;
        byte[] buffer = new byte[4096]; // Create a buffer for copying
        FileInputStream inputStream = null;
        ZipEntry zipEntry = null;
        for (File f : listFiles) {
            try {
                inputStream = new FileInputStream(f);
                zipEntry = new ZipEntry(f.getPath());
                zipOutputStream.putNextEntry(zipEntry);
                while ((byteReads = inputStream.read(buffer)) != -1)
                    zipOutputStream.write(buffer, 0, byteReads);
            } finally {
                inputStream.close();
            }
        }
    } finally {
        zipOutputStream.close();
    }

    file = new File("exportCategory.zip");
    InputStream fileInputStream = new FileInputStream(file);
    return fileInputStream;
}

From source file:org.etudes.jforum.view.admin.ImportExportAction.java

/**
 * @param inputFile//from   ww w.  ja  v  a  2 s . c  o  m
 *            - file to zip
 * @param zout
 *            - zip output stream
 * @throws FileNotFoundException
 * @throws IOException
 */
private void writeToZip(File inputFile, ZipOutputStream zout, String baseFileName)
        throws FileNotFoundException, IOException {
    File files[] = inputFile.listFiles();
    for (int i = 0; i < files.length; i++) {
        if (files[i].isFile()) {
            FileInputStream in = new FileInputStream(files[i]);

            String name = null;
            String filepath = files[i].getAbsolutePath();
            name = filepath.substring(filepath.indexOf(baseFileName) + baseFileName.length() + 1);
            zout.putNextEntry(new ZipEntry(name));

            // Transfer bytes from the file to the ZIP file
            int len;
            byte buf[] = new byte[102400];
            while ((len = in.read(buf)) > 0) {
                zout.write(buf, 0, len);
            }
            zout.closeEntry();
            in.close();
        } else {
            writeToZip(files[i], zout, baseFileName);
        }
    }
}

From source file:org.etudes.mneme.impl.SubmissionServiceImpl.java

/**
 * Add the body of an attachment file to the zip stream.
 * //from  w  w  w.  ja v  a  2 s . co m
 * @param zip
 *        The zip stream.
 * @param key
 *        The root of the zip entry name.
 * @param attachment
 *        The attachment reference.
 * @param count
 *        The attachment count (used in the zip name).
 * @param indexHtml
 *        add a line about the attachment to this index html.
 */
protected void zipAttachment(ZipOutputStream zip, String key, Reference attachment, int count,
        StringBuilder indexHtml) {
    InputStream content = null;

    try {
        // security advisor
        pushAdvisor();

        // get a usable file name for the attachment
        String fileName = Validator.getFileName(attachment.getId());
        fileName = Validator.escapeResourceName(fileName);

        // Reference does not know how to make the id from a private docs reference.
        String id = attachment.getId();
        if (id.startsWith("/content/")) {
            id = id.substring("/content".length());
        }

        // get the attachment
        ContentResource resource = this.contentHostingService.getResource(id);

        // get the body
        content = resource.streamContent();
        if (content != null) {
            // start a zip entry
            String fname = key + " attachment " + Integer.toString(count++) + " " + fileName;
            zip.putNextEntry(new ZipEntry(fname));

            // read chunks of the body
            byte[] chunk = new byte[STREAM_BUFFER_SIZE];
            int lenRead;
            while ((lenRead = content.read(chunk)) != -1) {
                zip.write(chunk, 0, lenRead);
            }

            // close the zip entry
            zip.closeEntry();

            if (indexHtml != null) {
                indexHtml.append("<li><a href=\"" + fname + "\">" + fileName + "</a></li>\n");
            }
        }
    } catch (IdUnusedException e) {
        M_log.warn("zipAttachment: " + e.toString());
    } catch (PermissionException e) {
        M_log.warn("zipAttachment: " + e.toString());
    } catch (TypeException e) {
        M_log.warn("zipAttachment: " + e.toString());
    } catch (IOException e) {
        M_log.warn("zipAttachment: " + e.toString());
    } catch (ServerOverloadException e) {
        M_log.warn("zipAttachment: " + e.toString());
    } finally {
        // close the body stream
        if (content != null) {
            try {
                content.close();
            } catch (IOException e) {
                M_log.warn("zipAttachment: closing stream: " + e.toString());
            }
        }

        // clear the security advisor
        popAdvisor();
    }
}

From source file:edu.lternet.pasta.datapackagemanager.DataPackageArchive.java

/**
 * Generate an "archive" of the data package by parsing and retrieving
 * components of the data package resource map
 * //w w w  .  j a va 2s  .  co m
 * @param scope
 *          The scope value of the data package
 * @param identifier
 *          The identifier value of the data package
 * @param revision
 *          The revision value of the data package
 * @param map
 *          The resource map of the data package
 * @param authToken
 *          The authentication token of the user requesting the archive
 * @param transaction
 *          The transaction id of the request
 * @return The file name of the data package archive
 * @throws Exception
 */
public String createDataPackageArchive(String scope, Integer identifier, Integer revision, String userId,
        AuthToken authToken, String transaction) throws Exception {

    String zipName = transaction + ".zip";
    String zipPath = tmpDir + "/";

    EmlPackageId emlPackageId = new EmlPackageId(scope, identifier, revision);

    StringBuffer manifest = new StringBuffer();

    Date now = new Date();
    manifest.append("Manifest file for " + zipName + " created on " + now.toString() + "\n");

    DataPackageManager dpm = null;

    /*
     * It is necessary to create a temporary file while building the ZIP archive
     * to prevent the client from accessing an incomplete product.
     */
    String tmpName = DigestUtils.md5Hex(transaction);
    File zFile = new File(zipPath + tmpName);

    if (zFile.exists()) {
        String gripe = "The resource " + zipName + "already exists!";
        throw new ResourceExistsException(gripe);
    }

    try {
        dpm = new DataPackageManager();
    } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
        throw e;
    }

    FileOutputStream fOut = null;

    try {
        fOut = new FileOutputStream(zFile);
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    if (dpm != null && fOut != null) {

        String map = null;

        try {
            map = dpm.readDataPackage(scope, identifier, revision.toString(), authToken, userId);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            throw e;
        }

        Scanner mapScanner = new Scanner(map);

        ZipOutputStream zOut = new ZipOutputStream(fOut);

        while (mapScanner.hasNextLine()) {

            FileInputStream fIn = null;
            String objectName = null;
            File file = null;

            String line = mapScanner.nextLine();

            if (line.contains(URI_MIDDLE_METADATA)) {

                try {
                    file = dpm.getMetadataFile(scope, identifier, revision.toString(), userId, authToken);
                    objectName = emlPackageId.toString() + ".xml";
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            } else if (line.contains(URI_MIDDLE_REPORT)) {

                try {
                    file = dpm.readDataPackageReport(scope, identifier, revision.toString(), emlPackageId,
                            authToken, userId);
                    objectName = emlPackageId.toString() + ".report.xml";
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            } else if (line.contains(URI_MIDDLE_DATA)) {

                String[] lineParts = line.split("/");
                String entityId = lineParts[lineParts.length - 1];
                String dataPackageResourceId = DataPackageManager.composeResourceId(ResourceType.dataPackage,
                        scope, identifier, revision, null);
                String entityResourceId = DataPackageManager.composeResourceId(ResourceType.data, scope,
                        identifier, revision, entityId);

                String entityName = null;
                String xml = null;

                try {
                    entityName = dpm.readDataEntityName(dataPackageResourceId, entityResourceId, authToken);
                    xml = dpm.readMetadata(scope, identifier, revision.toString(), userId, authToken);
                    objectName = dpm.findObjectName(xml, entityName);
                    file = dpm.getDataEntityFile(scope, identifier, revision.toString(), entityId, authToken,
                            userId);
                } catch (UnauthorizedException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                    manifest.append(objectName + " (access denied)\n");
                } catch (ResourceNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            }

            if (objectName != null && fIn != null) {

                ZipEntry zipEntry = new ZipEntry(objectName);

                try {
                    zOut.putNextEntry(zipEntry);

                    int length;
                    byte[] buffer = new byte[1024];

                    while ((length = fIn.read(buffer)) > 0) {
                        zOut.write(buffer, 0, length);
                    }

                    zOut.closeEntry();
                    fIn.close();

                } catch (IOException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

            }

        }

        // Create ZIP archive manifest
        File mFile = new File(zipPath + transaction + ".txt");
        FileUtils.writeStringToFile(mFile, manifest.toString());
        ZipEntry zipEntry = new ZipEntry("manifest.txt");

        try {

            FileInputStream fIn = new FileInputStream(mFile);
            zOut.putNextEntry(zipEntry);

            int length;
            byte[] buffer = new byte[1024];

            while ((length = fIn.read(buffer)) > 0) {
                zOut.write(buffer, 0, length);
            }

            zOut.closeEntry();
            fIn.close();

        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }

        // Close ZIP archive
        zOut.close();

        FileUtils.forceDelete(mFile);

    }

    File tmpFile = new File(zipPath + tmpName);
    File zipFile = new File(zipPath + zipName);

    // Copy hidden ZIP archive to visible ZIP archive, thus making available
    if (!tmpFile.renameTo(zipFile)) {
        String gripe = "Error renaming " + tmpName + " to " + zipName + "!";
        throw new IOException();
    }

    return zipName;

}

From source file:lu.fisch.unimozer.Diagram.java

private void addToZip(ZipOutputStream zo, String baseDir, File directory)
        throws FileNotFoundException, IOException {
    // get all files
    File[] files = directory.listFiles();
    for (int f = 0; f < files.length; f++) {
        if (files[f].isDirectory()) {
            String entry = files[f].getAbsolutePath();
            entry = entry.substring(directory.getAbsolutePath().length() + 1);
            addToZip(zo, baseDir + entry + "/", files[f]);
        } else {/*from  w w  w  . jav a  2  s .  c  o  m*/
            //System.out.println("File = "+files[f].getAbsolutePath());
            //System.out.println("List = "+Arraysv.deepToString(excludeExtention));
            //System.out.println("We got = "+getExtension(files[f]));
            FileInputStream bi = new FileInputStream(files[f]);

            String entry = files[f].getAbsolutePath();
            entry = entry.substring(directory.getAbsolutePath().length() + 1);
            entry = baseDir + entry;
            ZipEntry ze = new ZipEntry(entry);
            zo.putNextEntry(ze);
            byte[] buf = new byte[1024];
            int anz;
            while ((anz = bi.read(buf)) != -1) {
                zo.write(buf, 0, anz);
            }
            zo.closeEntry();
            bi.close();
        }
    }
}

From source file:lu.fisch.unimozer.Diagram.java

/**
 * http://snippets.dzone.com/posts/show/3468
 * modified to create the zip file if it does not exist
 * // w  w  w .  jav a2  s .c o  m
 * @param zipFile
 * @param files
 * @throws IOException
 */
public void addFilesToExistingZip(File zipFile, String baseDir, File directory) throws IOException {
    ZipOutputStream out;
    File tempFile = null;

    byte[] buf = new byte[1024];
    boolean delete = false;

    if (zipFile.exists()) {
        delete = true;
        // get a temp file
        tempFile = File.createTempFile(zipFile.getName(), null);
        // delete it, otherwise you cannot rename your existing zip to it.
        tempFile.delete();

        boolean renameOk = zipFile.renameTo(tempFile);
        if (!renameOk) {
            throw new RuntimeException("could not rename the file " + zipFile.getAbsolutePath() + " to "
                    + tempFile.getAbsolutePath());
        }

        ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
        out = new ZipOutputStream(new FileOutputStream(zipFile));

        ZipEntry entry = zin.getNextEntry();
        while (entry != null) {
            String name = entry.getName();
            boolean notInFiles = true;
            /*
            for (File f : files)
            {
            if (f.getName().equals(name))
            {
                notInFiles = false;
                break;
            }
            }*/
            if (notInFiles) {
                // Add ZIP entry to output stream.
                out.putNextEntry(new ZipEntry(name));
                // Transfer bytes from the ZIP file to the output file
                int len;
                while ((len = zin.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            }
            entry = zin.getNextEntry();
        }
        // Close the streams
        zin.close();
    } else {
        out = new ZipOutputStream(new FileOutputStream(zipFile));
    }
    /*
    // Compress the files
    for (int i = 0; i < files.length; i++)
    {
    InputStream in = new FileInputStream(files[i]);
    // Add ZIP entry to output stream.
    out.putNextEntry(new ZipEntry(files[i].getName()));
    // Transfer bytes from the file to the ZIP file
    int len;
    while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
    }
    // Complete the entry
    out.closeEntry();
    in.close();
    }
    */

    addToZip(out, baseDir, directory);

    // Complete the ZIP file
    out.close();

    if (delete == true)
        tempFile.delete();
}

From source file:org.exoplatform.forum.service.impl.JCRDataStorage.java

public Object exportXML(String categoryId, String forumId, List<String> objectIds, String nodePath,
        ByteArrayOutputStream bos, boolean isExportAll) throws Exception {
    SessionProvider sProvider = CommonUtils.createSystemProvider();
    try {//from  www  . j  av  a 2 s  .  co  m
        List<File> listFiles = new ArrayList<File>();

        if (!isExportAll) {
            if (categoryId != null) {
                if (Utils.isEmpty(forumId)) {
                    listFiles.addAll(createForumFiles(categoryId, objectIds, sProvider));
                } else {
                    Node categoryHome = getCategoryHome(sProvider);
                    categoryHome.getSession().exportSystemView(nodePath, bos, false, false);
                    return null;
                }
            } else {
                listFiles.addAll(createCategoryFiles(objectIds, sProvider));
            }
        } else {
            listFiles.addAll(createAllForumFiles(sProvider));
        }

        ZipOutputStream zipOutputStream = null;
        try {
            zipOutputStream = new ZipOutputStream(new FileOutputStream("exportCategory.zip"));
            int byteReads;
            byte[] buffer = new byte[4096]; // Create a buffer for copying
            FileInputStream inputStream = null;
            ZipEntry zipEntry = null;
            for (File f : listFiles) {
                inputStream = new FileInputStream(f);
                try {
                    zipEntry = new ZipEntry(f.getPath());
                    zipOutputStream.putNextEntry(zipEntry);
                    while ((byteReads = inputStream.read(buffer)) != -1)
                        zipOutputStream.write(buffer, 0, byteReads);
                } finally {
                    inputStream.close();
                }
            }

        } finally {
            zipOutputStream.close();
        }
        File file = new File("exportCategory.zip");
        for (File f : listFiles)
            f.deleteOnExit();
        return file;
    } catch (Exception e) {
        return null;
    }
}

From source file:edu.harvard.iq.dvn.core.web.subsetting.AnalysisPage.java

public void zipFiles(OutputStream out, List<File> fllst) {
    ZipOutputStream zout = null;
    //BufferedInputStream infile = null;
    FileInputStream infile = null;

    zout = new ZipOutputStream(out);

    for (int i = 0; i < fllst.size(); i++) {
        try {//from   w ww.  j  a  va 2  s  . c o m
            infile = new FileInputStream(fllst.get(i));//new BufferedInputStream()

        } catch (FileNotFoundException e) {
            err.println("input file is not found");
            e.printStackTrace();
            try {
                zout.close();
            } catch (ZipException ze) {
                err.println("zip file invalid");
                ze.printStackTrace();
            } catch (IOException ex) {
                err.println("closing output file");
                ex.printStackTrace();
            }
        }

        ZipEntry ze = new ZipEntry(fllst.get(i).getName());
        try {
            zout.putNextEntry(ze);
            /*
                int len;
                while ((len = infile.read())> 0) {
            zout.write(len);
                }
            */

            byte[] dataBuffer = new byte[8192];

            int k = 0;
            while ((k = infile.read(dataBuffer)) > 0) {
                zout.write(dataBuffer, 0, k);
                //fileSize += i; 
                out.flush();
            }

        } catch (ZipException zpe) {
            zpe.printStackTrace();
            err.println("zip file is invalid");
        } catch (IOException ie) {
            ie.printStackTrace();
            err.println("output file io-error");
        }

        try {
            infile.close();
        } catch (IOException ie) {
            err.println("error: closing input file");
        }
    }

    try {
        zout.close();
    } catch (ZipException zpe) {
        err.println("zip file invalid");
        zpe.printStackTrace();
    } catch (IOException ioe) {
        err.println("error closing zip file");
        ioe.printStackTrace();
    }

}