Example usage for java.util.zip ZipOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP output stream as well as the stream being filtered.

Usage

From source file:com.microsoft.tfs.client.common.ui.teambuild.commands.CreateUploadZipCommand.java

/**
 * Zip a file or folder to a zip file/* w  w  w.  jav a 2 s  .c  o m*/
 *
 *
 * @param srcFolder
 * @param destZipFile
 * @throws Exception
 */
public void zip(final String srcFolder, final String destZipFile) throws Exception {
    checkFolder(localPath);
    final FileOutputStream fileWriter = new FileOutputStream(destZipFile);
    final ZipOutputStream zipout = new ZipOutputStream(fileWriter);

    try {
        loadIgnoreFile(srcFolder);

        /* preserve the folder when archive */
        final String parentPath = LocalPath
                .removeTrailingSeparators(new File(srcFolder).getParentFile().getAbsolutePath());
        addFileToZip(parentPath, new File(srcFolder).getAbsoluteFile(), zipout);
        zipout.flush();
    } catch (final Exception e) {
        errorMsg = MessageFormat.format(
                Messages.getString("CreateUploadZipCommand.CreateArchiveErrorMessageFormat"), //$NON-NLS-1$
                srcFolder);
        log.error("Exceptions when creating zip archive ", e); //$NON-NLS-1$
        throw e;
    } finally {
        zipout.close();
    }
}

From source file:net.morphbank.mbsvc3.webservices.Uploader.java

private String createZipFile() {
    String fileName = folderPath + "xml" + getNextReqFileNumber(folderPath) + ".zip";
    String list = "";
    try {//from   w w w . j  a  v a2 s. com
        FileOutputStream fout = new FileOutputStream(fileName);
        ZipOutputStream zout = new ZipOutputStream(fout);

        for (int i = 0; i < listOfXmlFiles.size(); i++) {
            String file = listOfXmlFiles.get(i);

            if (file.endsWith(".xml")) {
                list += file;
                FileInputStream fin = new FileInputStream(listOfXmlFiles.get(i));
                ZipEntry ze = new ZipEntry(listOfXmlFiles.get(i).replaceAll(folderPath, ""));
                zout.putNextEntry(ze);
                for (int c = fin.read(); c != -1; c = fin.read()) {
                    zout.write(c);
                }
                fin.close();
            }

        }
        zout.close();
        fout.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return fileName.replaceAll(folderPath, "");

}

From source file:net.gbmb.collector.example.SimpleLogPush.java

private String storeArchive(Collection collection) throws IOException {
    String cid = collection.getId();
    java.util.Collection<CollectionRecord> records = collectionRecords.get(cid);

    // index//from w ww  . jav  a2 s  .co m
    ByteArrayOutputStream indexStream = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
    PrintStream output = new PrintStream(indexStream);
    // zip
    ByteArrayOutputStream archiveStream = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
    ZipOutputStream zos = new ZipOutputStream(archiveStream);
    output.println("Serialize collection: " + collection.getId());
    output.println("  creation date: " + collection.getCreationDate());
    output.println("  end date:      " + collection.getEndDate());
    for (CollectionRecord cr : records) {
        output.print(cr.getRecordDate());
        output.print(" ");
        output.println(cr.getContent());
        if (cr.getAttachment() != null) {
            String attName = cr.getAttachment();
            output.println("  > " + attName);
            ZipEntry entry = new ZipEntry(cr.getAttachment());
            zos.putNextEntry(entry);
            InputStream content = temporaryStorage.get(cid, attName);
            IOUtils.copy(content, zos);
        }
    }
    // add the index file
    output.close();
    ZipEntry index = new ZipEntry("index");
    zos.putNextEntry(index);
    IOUtils.write(indexStream.toByteArray(), zos);
    // close zip
    zos.close();
    ByteArrayInputStream content = new ByteArrayInputStream(archiveStream.toByteArray());

    // send to final storage
    return finalStorage.store(cid, content);
}

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  . ja va  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.glanznig.beepme.data.DataExporter.java

private String zipFiles(File zipFile, List<File> fileList) {
    String path = null;//from ww  w  .j  a va  2  s .com

    if (zipFile != null && fileList != null) {
        try {
            BufferedInputStream bufIn = null;
            FileOutputStream zipFOutStream = new FileOutputStream(zipFile);
            ZipOutputStream outStream = new ZipOutputStream(new BufferedOutputStream(zipFOutStream));

            byte data[] = new byte[BUFFER];
            Iterator<File> i = fileList.iterator();

            while (i.hasNext()) {
                File f = i.next();
                FileInputStream fIn = new FileInputStream(f);
                bufIn = new BufferedInputStream(fIn, BUFFER);
                ZipEntry entry = new ZipEntry(f.getName());
                outStream.putNextEntry(entry);
                int count;
                while ((count = bufIn.read(data, 0, BUFFER)) != -1) {
                    outStream.write(data, 0, count);
                }
                bufIn.close();
            }
            outStream.close();

            path = zipFile.getAbsolutePath();

        } catch (Exception e) {
            Log.e(TAG, "error while zipping.", e);
        }
    }

    return path;
}

From source file:edu.ku.brc.specify.tools.webportal.BuildSearchIndex2.java

License:asdf

private void buildZipFile() {
    try {/*  www  .j  a v  a 2  s.c  o m*/
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFileName));
        File src = new File(writeToDir);
        addToZip(out, src, "");
        out.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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

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

    reverseZOrders(top);//w  w w . j ava 2  s . c o  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:com.eviware.soapui.integration.exporter.ProjectExporter.java

/**
 * Compress temporary directory and save it on given path.
 * /*from ww  w .  j a  v  a 2s.c  o  m*/
 * @param exportPath
 * @return
 * @throws IOException
 */
private boolean packageAll(String exportPath) {
    if (!exportPath.endsWith(".zip"))
        exportPath = exportPath + ".zip";

    BufferedInputStream origin = null;
    ZipOutputStream out;
    boolean result = true;
    try {
        FileOutputStream dest = new FileOutputStream(exportPath);
        out = new ZipOutputStream(new BufferedOutputStream(dest));
        byte data[] = new byte[BUFFER];
        // get a list of files from current directory

        String files[] = tmpDir.list();

        for (int i = 0; i < files.length; i++) {
            //            System.out.println( "Adding: " + files[i] );
            FileInputStream fi = new FileInputStream(new File(tmpDir, files[i]));
            origin = new BufferedInputStream(fi, BUFFER);
            ZipEntry entry = new ZipEntry(files[i]);
            out.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
        }
        out.close();
    } catch (IOException e) {
        // TODO: handle exception
        result = false;
    }
    return result;
}

From source file:fr.gael.dhus.service.job.SendLogsJob.java

@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    if (!configurationManager.getSendLogsCronConfiguration().isActive())
        return;/*from ww w.  ja  v  a 2  s  .  c o  m*/
    long start = System.currentTimeMillis();
    logger.info("SCHEDULER : Send Administrative logs.");
    if (!DHuS.isStarted()) {
        logger.warn("SCHEDULER : Not run while system not fully initialized.");
        return;
    }

    String[] addresses = configurationManager.getSendLogsCronConfiguration().getAddresses().split(",");
    // Case of no addresses available: use system support
    if ((addresses == null) || (addresses.length == 0) || "".equals(addresses[0].trim())) {
        String email = configurationManager.getSupportConfiguration().getMail();
        if ((email == null) || "".equals(email)) {
            throw new MailException("Support e-mail not configured, " + "system logs will not be send");
        }
        addresses = new String[] { email };
    }

    RollingFileAppender rollingFileAppender = (RollingFileAppender) ((org.apache.logging.log4j.core.Logger) LogManager
            .getRootLogger()).getAppenders().get("RollingFile");
    if (rollingFileAppender == null) {
        throw new MailException("No rolling log file defined");
    }

    String logPath = rollingFileAppender.getFileName();

    if ((logPath == null) || logPath.trim().equals("")) {
        throw new MailException("Log file not defined");
    }

    File logs = new File(logPath);
    if (!logs.exists()) {
        throw new MailException("Log file not present : " + logs.getPath());
    }

    Date now = new Date();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'@'HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    String docFilename = configurationManager.getNameConfiguration().getShortName().toLowerCase() + "-"
            + df.format(now);

    File zipLogs;
    try {
        zipLogs = File.createTempFile(docFilename, ".zip");
    } catch (IOException e) {
        throw new MailException("Cannot create temporary zip log file.", e);
    }

    // compress logs file to zip format
    FileOutputStream fos;
    ZipOutputStream zos = null;
    FileInputStream fis = null;
    try {
        int length;
        byte[] buffer = new byte[1024];
        ZipEntry entry = new ZipEntry(docFilename + ".txt");

        fos = new FileOutputStream(zipLogs);
        zos = new ZipOutputStream(fos);
        fis = new FileInputStream(logs);

        zos.setLevel(Deflater.BEST_COMPRESSION);
        zos.putNextEntry(entry);
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
    } catch (IOException e) {
        throw new MailException("An error occurred during compression " + "logs file, cannot send logs !", e);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (zos != null) {
                zos.closeEntry();
                zos.close();
            }
        } catch (IOException e) {
            throw new MailException("An error occurred during compression " + "logs file, cannot send logs !",
                    e);
        }
    }

    EmailAttachment attachment = new EmailAttachment();
    attachment.setDescription(
            configurationManager.getNameConfiguration().getShortName() + " Logs " + now.toString());
    attachment.setPath(zipLogs.getPath());
    attachment.setName(zipLogs.getName());

    // Prepare the addresses
    List<String> ads = new ArrayList<String>();
    for (String email : addresses) {
        StringTokenizer tk = new StringTokenizer(email, ", ");
        while (tk.hasMoreTokens()) {
            String token = tk.nextToken().trim();
            if (!token.isEmpty())
                ads.add(token);
        }
    }
    for (String email : ads) {
        try {
            String server = configurationManager.getServerConfiguration().getExternalHostname();
            String url = configurationManager.getServerConfiguration().getExternalUrl();

            mailServer.send(email, null, null,
                    "[" + configurationManager.getNameConfiguration().getShortName().toLowerCase() + "@"
                            + server + "] logs of " + df.format(now),
                    "Here is attached " + configurationManager.getNameConfiguration().getShortName()
                            + " logs of \"" + url + "\" host.\n\n" + "Kind Regards.\nThe "
                            + configurationManager.getNameConfiguration().getShortName() + " Team.",
                    attachment);
            logger.info("Logs Sent to " + email);
        } catch (EmailException e) {
            throw new MailException("Cannot send logs to " + email, e);
        }
    }

    if (!zipLogs.delete()) {
        logger.warn("Cannot remove mail attachment: " + zipLogs.getAbsolutePath());
    }

    logger.info("SCHEDULER : Send Administrative logs done - " + (System.currentTimeMillis() - start) + "ms");
}

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   w  w  w. j a  v  a 2  s  .  c  om*/
 * @param dir {@link String}
 * @param zipfile {@link String}
 * @param excludeBatchXml boolean
 * @throws IOException 
 * @throws IllegalArgumentException in case of error
 */
public static void zipDirectory(final String dir, final String zipfile, final boolean excludeBatchXml)
        throws IOException, IllegalArgumentException {
    // Check that the directory is a directory, and get its contents
    File directory = new File(dir);
    if (!directory.isDirectory()) {
        throw new IllegalArgumentException("Not a directory:  " + dir);
    }
    String[] entries = directory.list();
    byte[] buffer = new byte[UtilConstants.BUFFER_CONST]; // Create a buffer for copying
    int bytesRead;

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));

    for (int index = 0; index < entries.length; index++) {
        if (excludeBatchXml && entries[index].contains(IUtilCommonConstants.BATCH_XML)) {
            continue;
        }
        File file = new File(directory, entries[index]);
        if (file.isDirectory()) {
            continue;// Ignore directory
        }
        FileInputStream input = new FileInputStream(file); // Stream to read file
        ZipEntry entry = new ZipEntry(file.getName()); // Make a ZipEntry
        out.putNextEntry(entry); // Store entry
        bytesRead = input.read(buffer);
        while (bytesRead != -1) {
            out.write(buffer, 0, bytesRead);
            bytesRead = input.read(buffer);
        }
        if (input != null) {
            input.close();
        }
    }
    if (out != null) {
        out.close();
    }
}