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.thoughtworks.go.util.ZipUtil.java

void addToZip(ZipPath path, File srcFile, ZipOutputStream zip, boolean excludeRootDir) throws IOException {
    if (srcFile.isDirectory()) {
        addFolderToZip(path, srcFile, zip, excludeRootDir);
    } else {//w w w . ja va 2  s  .co m
        byte[] buff = new byte[4096];
        try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(srcFile))) {
            ZipEntry zipEntry = path.with(srcFile).asZipEntry();
            zipEntry.setTime(srcFile.lastModified());
            zip.putNextEntry(zipEntry);
            int len;
            while ((len = inputStream.read(buff)) > 0) {
                zip.write(buff, 0, len);
            }
        }
    }
}

From source file:net.sourceforge.tagsea.instrumentation.network.NetworkSendJob.java

private File compressLogs(File[] filesToCompress) throws IOException {
    IPath stateLocation = TagSEAInstrumentationPlugin.getDefault().getStateLocation();
    DateFormat format = DateUtils.getDateFormat();
    String sendName = format.format(new Date()).replace('/', '-') + "-workspace"
            + stateLocation.toPortableString().hashCode() + ".zip";
    File sendFile = stateLocation.append(sendName).toFile();
    if (!sendFile.exists()) {
        sendFile.createNewFile();/*w w w. j  a v a2s  .c o m*/
    }
    if (filesToCompress.length == 0) {
        sendFile.delete();
        return null;
    }
    ZipOutputStream zipStream;
    zipStream = new ZipOutputStream(new FileOutputStream(sendFile));

    for (File file : filesToCompress) {
        FileInputStream inputStream = null;
        try {
            ZipEntry entry = new ZipEntry(file.getName());
            zipStream.putNextEntry(entry);
            inputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int read = -1;
            while ((read = inputStream.read(buffer)) != -1) {
                zipStream.write(buffer, 0, read);
            }

            zipStream.closeEntry();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
    zipStream.close();
    return sendFile;
}

From source file:net.librec.util.FileUtil.java

/**
 * Zip a given folder/*from   www  . ja va  2s  . co  m*/
 *
 * @param dirPath    a given folder: must be all files (not sub-folders)
 * @param filePath   zipped file
 * @throws Exception if error occurs
 */
public static void zipFolder(String dirPath, String filePath) throws Exception {
    File outFile = new File(filePath);
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outFile));
    int bytesRead;
    byte[] buffer = new byte[1024];
    CRC32 crc = new CRC32();
    for (File file : listFiles(dirPath)) {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        crc.reset();
        while ((bytesRead = bis.read(buffer)) != -1) {
            crc.update(buffer, 0, bytesRead);
        }
        bis.close();

        // Reset to beginning of input stream
        bis = new BufferedInputStream(new FileInputStream(file));
        ZipEntry entry = new ZipEntry(file.getName());
        entry.setMethod(ZipEntry.STORED);
        entry.setCompressedSize(file.length());
        entry.setSize(file.length());
        entry.setCrc(crc.getValue());
        zos.putNextEntry(entry);
        while ((bytesRead = bis.read(buffer)) != -1) {
            zos.write(buffer, 0, bytesRead);
        }
        bis.close();
    }
    zos.close();

    LOG.debug("A zip-file is created to: " + outFile.getPath());
}

From source file:com.sangupta.jerry.util.ZipUtils.java

/**
 * Compresses the provided file into ZIP format adding a '.ZIP' at the end
 * of the filename.// w  w w .j  a v  a  2  s. c  o  m
 * 
 * @param filePath
 *            the file path that needs to be compressed
 * 
 * @return returns the absolute path of the ZIP file.
 */
public String createZipFile(String filePath) {
    LOGGER.debug("Starting compression of " + filePath);

    String zipFilename = filePath + ".zip";
    LOGGER.debug("Creating zip file at " + zipFilename);

    byte[] buf = new byte[1024];

    ZipOutputStream stream = null;
    FileInputStream input = null;
    try {
        // Create the ZIP file
        stream = new ZipOutputStream(new FileOutputStream(zipFilename));

        // Compress the file
        File file = new File(filePath);
        input = new FileInputStream(file);

        // Add ZIP entry to output stream.
        stream.putNextEntry(new ZipEntry(file.getName()));

        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = input.read(buf)) > 0) {
            stream.write(buf, 0, len);
        }

        // Complete the entry
        stream.closeEntry();
    } catch (IOException e) {
        LOGGER.error("Unable to compress file " + filePath, e);
    } finally {
        IOUtils.closeQuietly(input);

        // Complete the ZIP file
        IOUtils.closeQuietly(stream);
    }

    return zipFilename;
}

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 . j ava2  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:de.jwi.zip.Zipper.java

public void zip(ZipOutputStream out, File f, File base) throws IOException {
    String name = f.getPath().replace('\\', '/');

    if (base != null) {
        String basename = base.getPath().replace('\\', '/');

        if (name.startsWith(basename)) {
            name = name.substring(basename.length());
        }//from   ww  w. j  a v a  2s . co m
    }

    if (name.startsWith("/")) {
        name = name.substring(1);
    }

    ZipEntry entry = new ZipEntry(name);
    entry.setTime(f.lastModified());

    out.putNextEntry(entry);

    FileInputStream is = new FileInputStream(f);

    byte[] buf = new byte[BUFSIZE];

    try {
        int l;
        while ((l = is.read(buf)) > -1) {
            out.write(buf, 0, l);
        }
    } finally {
        is.close();
    }
    out.closeEntry();

}

From source file:com.aionemu.commons.log4j.appenders.TruncateToZipFileAppender.java

/**
 * This method creates archive with file instead of deleting it.
 *
 * @param file file to truncate/*  w ww  . j  a  v a  2 s  .c  o m*/
 */
protected void truncate(File file) {
    LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started.");

    // Linux systems doesn't provide file creation time, so we have to hope
    // that log files
    // were not modified manually after server starup
    // We can use here Windowns-only solution but that suck :(
    if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) {
        File backupRoot = new File(getBackupDir());
        if (!backupRoot.exists() && !backupRoot.mkdirs()) {
            throw new AppenderInitializationError("Can't create backup dir for backup storage");
        }

        SimpleDateFormat df;
        try {
            df = new SimpleDateFormat(getBackupDateFormat());
        } catch (Exception e) {
            throw new AppenderInitializationError(
                    "Invalid date formate for backup files: " + getBackupDateFormat(), e);
        }
        String date = df.format(new Date(file.lastModified()));

        File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");

        ZipOutputStream zos = null;
        FileInputStream fis = null;
        try {
            zos = new ZipOutputStream(new FileOutputStream(zipFile));
            ZipEntry entry = new ZipEntry(file.getName());
            entry.setMethod(ZipEntry.DEFLATED);
            entry.setCrc(FileUtils.checksumCRC32(file));
            zos.putNextEntry(entry);
            fis = FileUtils.openInputStream(file);

            byte[] buffer = new byte[1024];
            int readed;
            while ((readed = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, readed);
            }

        } catch (Exception e) {
            throw new AppenderInitializationError("Can't create zip file", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    // not critical error
                    LogLog.warn("Can't close zip file", e);
                }
            }

            if (fis != null) {
                try {
                    // not critical error
                    fis.close();
                } catch (IOException e) {
                    LogLog.warn("Can't close zipped file", e);
                }
            }
        }

        if (!file.delete()) {
            throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath());
        }
    }
}

From source file:com.bibisco.manager.ProjectManager.java

public static void zipIt(String zipFile) {

    mLog.debug("Start zipIt(String)");

    ContextManager lContextManager = ContextManager.getInstance();

    String lStrDBDirectoryPath = lContextManager.getDbDirectoryPath();
    String lStrDbProjectDirectory = getDBProjectDirectory(lContextManager.getIdProject());
    List<String> lFileList = getDirectoryFileList(new File(lStrDbProjectDirectory));

    try {/*  w  w w. j a v a 2  s.  c  om*/
        File lFile = new File(zipFile);

        lFile.createNewFile();
        FileOutputStream lFileOutputStream = new FileOutputStream(lFile);
        ZipOutputStream lZipOutputStream = new ZipOutputStream(lFileOutputStream);

        byte[] buffer = new byte[1024];
        for (String lStrFile : lFileList) {

            ZipEntry lZipEntry = new ZipEntry(
                    lStrFile.substring(lStrDBDirectoryPath.length(), lStrFile.length()));
            lZipOutputStream.putNextEntry(lZipEntry);

            FileInputStream lFileInputStream = new FileInputStream(lStrFile);

            int lIntLen;
            while ((lIntLen = lFileInputStream.read(buffer)) > 0) {
                lZipOutputStream.write(buffer, 0, lIntLen);
            }

            lFileInputStream.close();
        }

        lZipOutputStream.closeEntry();
        lZipOutputStream.close();

        mLog.debug("Folder successfully compressed");
    } catch (IOException e) {
        mLog.error(e);
        throw new BibiscoException(e, BibiscoException.IO_EXCEPTION);
    }

    mLog.debug("End zipIt(String)");
}

From source file:it.isislab.sof.core.engine.hadoop.sshclient.connection.SofManager.java

private static void addDir(File dirObj, ZipOutputStream out, String dirToZip) throws IOException {
    File[] files = dirObj.listFiles();
    byte[] tmpBuf = new byte[1024];

    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory()) {
            addDir(files[i], out, dirToZip);
            continue;
        }/* ww w . j  av a  2  s  .c  o m*/

        FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
        System.out.println("Zipping: " + files[i].getName());
        String filename = files[i].getAbsolutePath().substring(dirToZip.length());
        out.putNextEntry(new ZipEntry(filename));
        int len;
        while ((len = in.read(tmpBuf)) > 0) {
            out.write(tmpBuf, 0, len);
        }
        out.closeEntry();
        in.close();
    }
}

From source file:com.l2jserver.service.core.logging.TruncateToZipFileAppender.java

/**
 * This method creates archive with file instead of deleting it.
 * //from w w w.  jav  a 2s  . c  o m
 * @param file
 *            file to truncate
 */
protected void truncate(File file) {
    LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started.");

    // Linux systems doesn't provide file creation time, so we have to hope
    // that log files
    // were not modified manually after server starup
    // We can use here Windowns-only solution but that suck :(
    if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) {
        File backupRoot = new File(getBackupDir());
        if (!backupRoot.exists() && !backupRoot.mkdirs()) {
            throw new Error("Can't create backup dir for backup storage");
        }

        SimpleDateFormat df;
        try {
            df = new SimpleDateFormat(getBackupDateFormat());
        } catch (Exception e) {
            throw new Error("Invalid date formate for backup files: " + getBackupDateFormat(), e);
        }
        String date = df.format(new Date(file.lastModified()));

        File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");

        ZipOutputStream zos = null;
        FileInputStream fis = null;
        try {
            zos = new ZipOutputStream(new FileOutputStream(zipFile));
            ZipEntry entry = new ZipEntry(file.getName());
            entry.setMethod(ZipEntry.DEFLATED);
            entry.setCrc(FileUtils.checksumCRC32(file));
            zos.putNextEntry(entry);
            fis = FileUtils.openInputStream(file);

            byte[] buffer = new byte[1024];
            int readed;
            while ((readed = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, readed);
            }

        } catch (Exception e) {
            throw new Error("Can't create zip file", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    // not critical error
                    LogLog.warn("Can't close zip file", e);
                }
            }

            if (fis != null) {
                try {
                    // not critical error
                    fis.close();
                } catch (IOException e) {
                    LogLog.warn("Can't close zipped file", e);
                }
            }
        }

        if (!file.delete()) {
            throw new Error("Can't delete old log file " + file.getAbsolutePath());
        }
    }
}