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:Main.java

public void doZip(String filename, String zipfilename) throws Exception {
    byte[] buf = new byte[1024];
    FileInputStream fis = new FileInputStream(filename);
    fis.read(buf, 0, buf.length);/*  w w w.  j  a va 2  s .c o  m*/

    CRC32 crc = new CRC32();
    ZipOutputStream s = new ZipOutputStream((OutputStream) new FileOutputStream(zipfilename));
    s.setLevel(6);

    ZipEntry entry = new ZipEntry(filename);
    entry.setSize((long) buf.length);
    crc.reset();
    crc.update(buf);
    entry.setCrc(crc.getValue());
    s.putNextEntry(entry);
    s.write(buf, 0, buf.length);
    s.finish();
    s.close();
}

From source file:b2s.idea.mavenize.JarCombiner.java

private void addServiceEntries(ZipOutputStream zipOut, JarContext context) throws IOException {
    for (Map.Entry<String, StringBuilder> entry : context.getServices()) {
        zipOut.putNextEntry(new ZipEntry(entry.getKey()));
        zipOut.write(entry.getValue().toString().getBytes());
        zipOut.closeEntry();//  w w w.j  a v  a 2  s.  co  m
    }
}

From source file:com.xpn.xwiki.plugin.packaging.AbstractPackageTest.java

/**
 * Create a XAR file using java.util.zip.
 *
 * @param docs The documents to include.
 * @param encodings The charset for each document.
 * @param packageXmlEncoding The encoding of package.xml
 * @return the XAR file as a byte array.
 *///from  w  w  w. j  a v  a 2  s . c  o  m
protected byte[] createZipFile(XWikiDocument docs[], String[] encodings, String packageXmlEncoding)
        throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry zipp = new ZipEntry("package.xml");
    zos.putNextEntry(zipp);
    zos.write(getEncodedByteArray(getPackageXML(docs, packageXmlEncoding), packageXmlEncoding));
    for (int i = 0; i < docs.length; i++) {
        String zipEntryName = docs[i].getSpace() + "/" + docs[i].getName();
        if (docs[i].getTranslation() != 0) {
            zipEntryName += "." + docs[i].getLanguage();
        }
        ZipEntry zipe = new ZipEntry(zipEntryName);
        zos.putNextEntry(zipe);
        String xmlCode = docs[i].toXML(false, false, false, false, getContext());
        zos.write(getEncodedByteArray(xmlCode, encodings[i]));
    }
    zos.finish();
    zos.close();
    return baos.toByteArray();
}

From source file:S3DataManager.java

public static void zipSource(final String directory, final ZipOutputStream out, final String prefixToTrim)
        throws Exception {
    if (!Paths.get(directory).startsWith(Paths.get(prefixToTrim))) {
        throw new Exception(zipSourceError + "prefixToTrim: " + prefixToTrim + ", directory: " + directory);
    }// w  w w.  j  av a 2 s  .  c  o  m

    File dir = new File(directory);
    String[] dirFiles = dir.list();
    if (dirFiles == null) {
        throw new Exception("Invalid directory path provided: " + directory);
    }
    byte[] buffer = new byte[1024];
    int bytesRead;

    for (int i = 0; i < dirFiles.length; i++) {
        File f = new File(dir, dirFiles[i]);
        if (f.isDirectory()) {
            if (f.getName().equals(".git") == false) {
                zipSource(f.getPath() + File.separator, out, prefixToTrim);
            }
        } else {
            FileInputStream inputStream = new FileInputStream(f);
            try {
                String path = trimPrefix(f.getPath(), prefixToTrim);

                ZipEntry entry = new ZipEntry(path);
                out.putNextEntry(entry);
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            } finally {
                inputStream.close();
            }
        }
    }
}

From source file:com.replaymod.sponge.recording.AbstractRecorder.java

@Override
public void addOutput(OutputStream out) throws IOException {
    ZipOutputStream zipOut = new ZipOutputStream(out);
    zipOut.putNextEntry(new ZipEntry("recording.tmcpr"));
    outputs.put(out, zipOut);//from   w ww  .j  av a  2s. c om
}

From source file:se.crisp.codekvast.agent.daemon.worker.impl.ZipFileDataExporterImpl.java

private void doExportDatabaseTable(ZipOutputStream zip, CSVWriter csvWriter, String table, String... columns)
        throws IOException {
    zip.putNextEntry(ExportFileEntry.fromString(table + ".csv").toZipEntry());
    csvWriter.writeNext(columns, false);

    String[] line = new String[columns.length];
    String sql = asList(columns).stream().collect(joining(", ", "SELECT ", " FROM " + table));
    jdbcTemplate.query(sql, rs -> {/* www .j  a  va  2s.  c o  m*/
        for (int i = 0; i < columns.length; i++) {
            line[i] = rs.getString(i + 1);
        }
        csvWriter.writeNext(line, false);
    });

    csvWriter.flush();
    zip.closeEntry();
}

From source file:be.fedict.eid.dss.portal.control.bean.UploadBean.java

@Override
public void listener(UploadEvent event) throws Exception {
    this.log.debug("listener");
    UploadItem item = event.getUploadItem();
    this.log.debug("filename: #0", item.getFileName());
    this.filename = item.getFileName();
    this.log.debug("content type: #0", item.getContentType());
    String extension = FilenameUtils.getExtension(this.filename).toLowerCase();
    this.contentType = supportedFileExtensions.get(extension);
    if (null == this.contentType) {
        /*//w  w  w .  j  a va 2  s.  c o m
         * Unsupported content-type is converted to a ZIP container.
         */
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        ZipEntry zipEntry = new ZipEntry(this.filename);
        zipOutputStream.putNextEntry(zipEntry);
        IOUtils.write(item.getData(), zipOutputStream);
        zipOutputStream.close();
        this.filename = FilenameUtils.getBaseName(this.filename) + ".zip";
        this.document = outputStream.toByteArray();
        this.contentType = "application/zip";
        return;
    }
    this.log.debug("file size: #0", item.getFileSize());
    this.log.debug("data bytes available: #0", (null != item.getData()));
    if (null != item.getData()) {
        this.document = item.getData();
        return;
    }
    File file = item.getFile();
    if (null != file) {
        this.log.debug("tmp file: #0", file.getAbsolutePath());
        this.document = FileUtils.readFileToByteArray(file);
    }
}

From source file:be.fedict.eid.dss.sp.servlet.UploadServlet.java

@Override
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOG.debug("doPost");

    String fileName = null;//w  ww  . j a v a 2 s. c  o m
    String contentType;
    byte[] document = null;

    FileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Parse the request
    try {
        List<FileItem> items = upload.parseRequest(request);
        if (!items.isEmpty()) {
            fileName = items.get(0).getName();
            // contentType = items.get(0).getContentType();
            document = items.get(0).get();
        }
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }

    String extension = FilenameUtils.getExtension(fileName).toLowerCase();
    contentType = supportedFileExtensions.get(extension);
    if (null == contentType) {
        /*
         * Unsupported content-type is converted to a ZIP container.
         */
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOutputStream.putNextEntry(zipEntry);
        IOUtils.write(document, zipOutputStream);
        zipOutputStream.close();
        fileName = FilenameUtils.getBaseName(fileName) + ".zip";
        document = outputStream.toByteArray();
        contentType = "application/zip";
    }

    LOG.debug("File name: " + fileName);
    LOG.debug("Content Type: " + contentType);

    String signatureRequest = new String(Base64.encode(document));

    request.getSession().setAttribute(DOCUMENT_SESSION_ATTRIBUTE, document);
    request.getSession().setAttribute("SignatureRequest", signatureRequest);
    request.getSession().setAttribute("ContentType", contentType);

    response.sendRedirect(request.getContextPath() + this.postPage);
}

From source file:se.crisp.codekvast.agent.daemon.worker.impl.ZipFileDataExporterImpl.java

private void doExportMetaInfo(ZipOutputStream zip, Charset charset, ExportFileMetaInfo metaInfo)
        throws IOException, IllegalAccessException {
    zip.putNextEntry(ExportFileEntry.META_INFO.toZipEntry());

    Set<String> lines = new TreeSet<>();
    FileUtils.extractFieldValuesFrom(metaInfo, lines);
    for (String line : lines) {
        zip.write(line.getBytes(charset));
        zip.write('\n');
    }//from  w ww . ja  v  a  2 s  .c  om
    zip.closeEntry();
}

From source file:com.yunmel.syncretic.utils.io.IOUtils.java

/**
 * ZIP?// www .  j av a2  s  .c  o  m
 * 
 * @param dirPath 
 * @param fileDir ?
 * @param zouts ?
 */
public static void zipDirectoryToZipFile(String dirPath, File fileDir, ZipOutputStream zouts) {
    if (fileDir.isDirectory()) {
        File[] files = fileDir.listFiles();
        // 
        if (files.length == 0) {
            // ?
            ZipEntry entry = new ZipEntry(getEntryName(dirPath, fileDir));
            try {
                zouts.putNextEntry(entry);
                zouts.closeEntry();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }

        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                // 
                IOUtils.zipFilesToZipFile(dirPath, files[i], zouts);
            } else {
                // 
                IOUtils.zipDirectoryToZipFile(dirPath, files[i], zouts);
            }
        }

    }

}