Example usage for java.util.zip ZipOutputStream ZipOutputStream

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

Introduction

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

Prototype

public ZipOutputStream(OutputStream out) 

Source Link

Document

Creates a new ZIP output stream.

Usage

From source file:com.heliosdecompiler.helios.tasks.DecompileAndSaveTask.java

@Override
public void run() {
    File file = FileChooserUtil.chooseSaveLocation(Settings.LAST_DIRECTORY.get().asString(),
            Collections.singletonList("zip"));
    if (file == null)
        return;//from  www .j a  v  a  2s . c om
    if (file.exists()) {
        boolean delete = SWTUtil.promptForYesNo(Constants.REPO_NAME + " - Overwrite existing file",
                "The selected file already exists. Overwrite?");
        if (!delete) {
            return;
        }
    }

    AtomicReference<Transformer> transformer = new AtomicReference<>();

    Display display = Display.getDefault();
    display.asyncExec(() -> {
        Shell shell = new Shell(Display.getDefault());
        FillLayout layout = new FillLayout();
        layout.type = SWT.VERTICAL;
        shell.setLayout(layout);
        Transformer.getAllTransformers(t -> {
            return t instanceof Decompiler || t instanceof Disassembler;
        }).forEach(t -> {
            Button button = new Button(shell, SWT.RADIO);
            button.setText(t.getName());
            button.addSelectionListener(new SelectionAdapter() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    transformer.set(t);
                }
            });
        });
        Button ok = new Button(shell, SWT.NONE);
        ok.setText("OK");
        ok.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                shell.close();
                shell.dispose();
                synchronized (transformer) {
                    transformer.notify();
                }
            }
        });
        shell.pack();
        SWTUtil.center(shell);
        shell.open();
    });

    synchronized (transformer) {
        try {
            transformer.wait();
        } catch (InterruptedException e) {
            ExceptionHandler.handle(e);
        }
    }

    FileOutputStream fileOutputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {
        file.createNewFile();
        fileOutputStream = new FileOutputStream(file);
        zipOutputStream = new ZipOutputStream(fileOutputStream);
        Set<String> written = new HashSet<>();
        for (Pair<String, String> pair : data) {
            LoadedFile loadedFile = Helios.getLoadedFile(pair.getValue0());
            if (loadedFile != null) {
                String innerName = pair.getValue1();
                byte[] bytes = loadedFile.getAllData().get(innerName);
                if (bytes != null) {
                    if (loadedFile.getClassNode(pair.getValue1()) != null) {
                        StringBuilder buffer = new StringBuilder();
                        transformer.get().transform(loadedFile.getClassNode(pair.getValue1()), bytes, buffer);
                        String name = innerName.substring(0, innerName.length() - 6) + ".java";
                        if (written.add(name)) {
                            zipOutputStream.putNextEntry(new ZipEntry(name));
                            zipOutputStream.write(buffer.toString().getBytes(StandardCharsets.UTF_8));
                            zipOutputStream.closeEntry();
                        } else {
                            SWTUtil.showMessage("Duplicate entry occured: " + name);
                        }
                    } else {
                        if (written.add(pair.getValue1())) {
                            zipOutputStream.putNextEntry(new ZipEntry(pair.getValue1()));
                            zipOutputStream.write(loadedFile.getAllData().get(pair.getValue1()));
                            zipOutputStream.closeEntry();
                        } else {
                            SWTUtil.showMessage("Duplicate entry occured: " + pair.getValue1());
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        ExceptionHandler.handle(e);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
    }
}

From source file:com.joliciel.lefff.LefffMemoryLoader.java

public void serializeMemoryBase(LefffMemoryBase memoryBase, File memoryBaseFile) {
    LOG.debug("serializeMemoryBase");
    boolean isZip = false;
    if (memoryBaseFile.getName().endsWith(".zip"))
        isZip = true;/* w w w .ja  v  a 2 s  .com*/

    FileOutputStream fos = null;
    ObjectOutputStream out = null;
    ZipOutputStream zos = null;
    try {
        fos = new FileOutputStream(memoryBaseFile);
        if (isZip) {
            zos = new ZipOutputStream(fos);
            zos.putNextEntry(new ZipEntry("lefff.obj"));
            out = new ObjectOutputStream(zos);
        } else {
            out = new ObjectOutputStream(fos);
        }

        try {
            out.writeObject(memoryBase);
        } finally {
            out.flush();
            out.close();
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:com.joliciel.jochre.lexicon.TextFileLexicon.java

public void serialize(File memoryBaseFile) {
    LOG.debug("serialize");
    boolean isZip = false;
    if (memoryBaseFile.getName().endsWith(".zip"))
        isZip = true;//from ww  w. j a  va 2 s  . c  om

    FileOutputStream fos = null;
    ObjectOutputStream out = null;
    ZipOutputStream zos = null;
    try {
        fos = new FileOutputStream(memoryBaseFile);
        if (isZip) {
            zos = new ZipOutputStream(fos);
            zos.putNextEntry(new ZipEntry("lexicon.obj"));
            out = new ObjectOutputStream(zos);
        } else {
            out = new ObjectOutputStream(fos);
        }

        try {
            out.writeObject(this);
        } finally {
            out.flush();
            out.close();
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:com.liferay.portal.deploy.hot.ExtHotDeployListener.java

private void zipWebInfJar(String zipName, File[] files) throws Exception {
    byte[] buffer = new byte[4096]; // Create a buffer for copying
    int bytesRead;

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipName));
    try {//from   w  w w  .j  a v  a2  s .  c  o m
        for (int i = 0; i < files.length; i++) {
            File f = files[i];
            if (f.isDirectory()) {
                continue;
            }

            String fileName = "WEB-INF/" + f.getName();
            FileInputStream in = new FileInputStream(f); // Stream to read file
            try {
                ZipEntry entry = new ZipEntry(fileName); // Make a ZipEntry
                out.putNextEntry(entry); // Store entry
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            } finally {
                in.close();
            }
        }
    } finally {
        out.close();
    }
}

From source file:br.univali.celine.lms.utils.zip.Zip.java

public void zipDir(String zipFileName, String dir) throws Exception {
    File dirObj = new File(dir);
    if (!dirObj.isDirectory()) {
        throw new Exception(dir + " is not a directory");
    }//  w w w .  j a  va  2s. c  o  m

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

    addDir(dirObj, out, dir.length() + 1);

    out.close();

}

From source file:com.edgenius.core.util.ZipFileUtil.java

/**
 * Creates a ZIP file and places it in the current working directory. The zip file is compressed
 * at the default compression level of the Deflater.
 * /*  w  ww  .j  av  a  2  s .  c  o m*/
 * @param listToZip. Key is file or directory, value is parent directory which will remove from given file/directory because 
 * compression only save relative directory.  For example, c:\geniuswiki\data\repository\somefile, if value is c:\geniuswiki, then only 
 * \data\repository\somefile will be saved.  It is very important, the value must be canonical path, ie, c:\my document\geniuswiki, 
 * CANNOT like this "c:\my doc~1\" 
 * 
 * 
 */
public static void createZipFile(String zipFileName, Map<File, String> listToZip, boolean withEmptyDir)
        throws ZipFileUtilException {
    ZipOutputStream zop = null;
    try {
        zop = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
        zop.setMethod(ZipOutputStream.DEFLATED);
        zop.setLevel(Deflater.DEFAULT_COMPRESSION);

        for (Entry<File, String> entry : listToZip.entrySet()) {
            File file = entry.getKey();
            if (!file.exists()) {
                log.warn("Unable to find file " + file + " to zip");
                continue;
            }
            if (file.isDirectory()) {
                Collection<File> list = FileUtils.listFiles(file, null, true);
                for (File src : list) {
                    addEntry(zop, src, createRelativeDir(src.getCanonicalPath(), entry.getValue()));
                }
                if (withEmptyDir) {
                    final List<File> emptyDirs = new ArrayList<File>();
                    if (file.list().length == 0) {
                        emptyDirs.add(file);
                    } else {
                        //I just don't know how quickly to find out all empty sub directories recursively. so use below hack:
                        FileUtils.listFiles(file, FileFilterUtils.falseFileFilter(), new IOFileFilter() {
                            //JDK1.6 @Override
                            public boolean accept(File f) {
                                if (!f.isDirectory())
                                    return false;

                                int size = f.listFiles().length;
                                if (size == 0) {
                                    emptyDirs.add(f);
                                }
                                return true;
                            }

                            //JDK1.6 @Override
                            public boolean accept(File arg0, String arg1) {
                                return true;
                            }
                        });
                    }
                    for (File src : emptyDirs) {
                        addEntry(zop, null, createRelativeDir(src.getCanonicalPath(), entry.getValue()));
                    }
                }
            } else {
                addEntry(zop, file, createRelativeDir(file.getCanonicalPath(), entry.getValue()));
            }

        }
    } catch (IOException e1) {
        throw new ZipFileUtilException(
                "An error has occurred while trying to zip the files. Error message is: ", e1);
    } finally {
        try {
            if (zop != null)
                zop.close();
        } catch (Exception e) {
        }
    }

}

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);//ww  w  .j  a v  a 2s.c o  m
}

From source file:hd3gtv.embddb.network.DataBlock.java

byte[] getBytes(Protocol protocol) throws IOException {
    checkIfNotEmpty();//w  w w  .jav a2  s  .com

    ByteArrayOutputStream byte_array_out_stream = new ByteArrayOutputStream(Protocol.BUFFER_SIZE);

    DataOutputStream dos = new DataOutputStream(byte_array_out_stream);
    dos.write(Protocol.APP_SOCKET_HEADER_TAG);
    dos.writeInt(Protocol.VERSION);

    /**
     * Start header name
     */
    dos.writeByte(0);
    byte[] request_name_data = request_name.getBytes(Protocol.UTF8);
    dos.writeInt(request_name_data.length);
    dos.write(request_name_data);

    /**
     * Start datas payload
     */
    dos.writeByte(1);

    /**
     * Get datas from zip
     */
    ZipOutputStream zos = new ZipOutputStream(dos);
    zos.setLevel(3);
    entries.forEach(entry -> {
        try {
            entry.toZip(zos);
        } catch (IOException e) {
            log.error("Can't add to zip", e);
        }
    });
    zos.flush();
    zos.finish();
    zos.close();

    dos.flush();
    dos.close();

    byte[] result = byte_array_out_stream.toByteArray();

    if (log.isTraceEnabled()) {
        log.trace("Make raw datas for " + request_name + Hexview.LINESEPARATOR + Hexview.tracelog(result));
    }

    return result;
}

From source file:com.joliciel.talismane.parser.ParsingConstrainerImpl.java

@Override
public void onCompleteParse() {
    if (this.transitionSystem == null)
        this.transitionSystem = TalismaneSession.getTransitionSystem();

    if (this.file != null) {
        try {//w  w  w. j a  v a2 s. c  o  m
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file, false));
            zos.putNextEntry(new ZipEntry("ParsingConstrainer.obj"));
            ObjectOutputStream oos = new ObjectOutputStream(zos);
            try {
                oos.writeObject(this);
            } finally {
                oos.flush();
            }
            zos.flush();
            zos.close();
        } catch (IOException ioe) {
            LogUtils.logError(LOG, ioe);
            throw new RuntimeException(ioe);
        }
    }
}

From source file:net.firejack.platform.core.utils.ArchiveUtils.java

/**
 *
 * @param file//www .  j  a  v a2 s  .  c  om
 * @return
 * @throws java.io.IOException
 */
public static InputStream create(File file) throws IOException {
    if (!file.exists())
        return null;

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ZipOutputStream out = new ZipOutputStream(stream);
    zipEntry(file, out, file.getPath());
    IOUtils.closeQuietly(out);

    return new ByteArrayInputStream(stream.toByteArray());
}