Example usage for java.util.zip ZipOutputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for writing the next entry.

Usage

From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Creates a zip archive of the currently serialized files in
 * getCurrentDirectory(), placing the archive in getArchiveDirectory().
 *
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getCurrentDirectory()/*from w ww.  j a va2s .c  o m*/
 * @see #getArchiveDirectory()
 */
public void archiveCurrentDirectory() throws RuntimeException {
    System.out.println("Making zip archive of files in " + getCurrentDirectory() + ", putting it in "
            + getArchiveDirectory() + ".");

    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
        throw new IllegalArgumentException("There is no " + current.getAbsolutePath() + " directory. "
                + "\nThis is where the serialized classes should be. "
                + "Please run serializeCurrentDirectory() first.");
    }

    File archive = new File(getArchiveDirectory());
    if (archive.exists() && !archive.isDirectory()) {
        throw new IllegalArgumentException(
                "Output directory " + archive.getAbsolutePath() + " is not a directory.");
    }

    if (!archive.exists()) {
        boolean success = archive.mkdirs();
    }

    String[] filenames = current.list();

    // Create a buffer for reading the files
    byte[] buf = new byte[1024];

    try {
        String version = Version.currentRepositoryVersion().toString();

        // Create the ZIP file
        String outFilename = "serializedclasses-" + version + ".zip";
        File _file = new File(getArchiveDirectory(), outFilename);
        FileOutputStream fileOut = new FileOutputStream(_file);
        ZipOutputStream out = new ZipOutputStream(fileOut);

        // Compress the files
        for (String filename : filenames) {
            File file = new File(current, filename);

            FileInputStream in = new FileInputStream(file);

            // Add ZIP entry to output stream.
            ZipEntry entry = new ZipEntry(filename);
            entry.setSize(file.length());
            entry.setTime(file.lastModified());

            out.putNextEntry(entry);

            // 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();
        }

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

        System.out.println("Finished writing zip file " + outFilename + ".");
    } catch (IOException e) {
        throw new RuntimeException("There was an I/O error associated with "
                + "the process of zipping up files in " + getCurrentDirectory() + ".", e);
    }
}

From source file:edu.cmu.tetradapp.util.TetradSerializableUtils.java

/**
 * Creates a zip archive of the currently serialized files in
 * getCurrentDirectory(), placing the archive in getArchiveDirectory().
 *
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getCurrentDirectory()/*from  w  w  w  . ja v  a2  s  .  c o m*/
 * @see #getArchiveDirectory()
 */
public void archiveCurrentDirectory() throws RuntimeException {
    System.out.println("Making zip archive of files in " + getCurrentDirectory() + ", putting it in "
            + getArchiveDirectory() + ".");

    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
        throw new IllegalArgumentException("There is no " + current.getAbsolutePath() + " directory. "
                + "\nThis is where the serialized classes should be. "
                + "Please run serializeCurrentDirectory() first.");
    }

    File archive = new File(getArchiveDirectory());
    if (archive.exists() && !archive.isDirectory()) {
        throw new IllegalArgumentException(
                "Output directory " + archive.getAbsolutePath() + " is not a directory.");
    }

    if (!archive.exists()) {
        archive.mkdirs();
    }

    String[] filenames = current.list();

    // Create a buffer for reading the files
    byte[] buf = new byte[1024];

    try {
        String version = Version.currentRepositoryVersion().toString();

        // Create the ZIP file
        String outFilename = "serializedclasses-" + version + ".zip";
        File _file = new File(getArchiveDirectory(), outFilename);
        FileOutputStream fileOut = new FileOutputStream(_file);
        ZipOutputStream out = new ZipOutputStream(fileOut);

        // Compress the files
        for (String filename : filenames) {
            File file = new File(current, filename);

            FileInputStream in = new FileInputStream(file);

            // Add ZIP entry to output stream.
            ZipEntry entry = new ZipEntry(filename);
            entry.setSize(file.length());
            entry.setTime(file.lastModified());

            out.putNextEntry(entry);

            // 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();
        }

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

        System.out.println("Finished writing zip file " + outFilename + ".");
    } catch (IOException e) {
        throw new RuntimeException("There was an I/O error associated with "
                + "the process of zipping up files in " + getCurrentDirectory() + ".", e);
    }
}

From source file:de.uni_koeln.spinfo.maalr.services.editor.server.EditorServiceImpl.java

public void export(Set<String> fields, EditorQuery query, File dest)
        throws NoDatabaseAvailableException, IOException {
    query.setCurrent(0);/*from ww  w  . j a  v a2  s  . c om*/
    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(dest));
    zout.putNextEntry(new ZipEntry("exported.tsv"));
    OutputStream out = new BufferedOutputStream(zout);
    OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
    for (String field : fields) {
        writer.write(field);
        writer.write("\t");
    }
    writer.write("\n");
    while (true) {
        LexEntryList result = Database.getInstance().queryForLexEntries(query.getUserOrIp(), query.getRole(),
                query.getVerification(), query.getVerifier(), query.getStartTime(), query.getEndTime(),
                query.getState(), query.getPageSize(), query.getCurrent(), query.getSortColumn(),
                query.isSortAscending());
        if (result == null || result.getEntries() == null || result.getEntries().size() == 0)
            break;
        for (LexEntry lexEntry : result.entries()) {
            addUserInfos(lexEntry);
            LemmaVersion version = lexEntry.getCurrent();
            write(writer, version, fields);
            writer.write("\n");
        }
        query.setCurrent(query.getCurrent() + query.getPageSize());
    }
    writer.flush();
    zout.closeEntry();
    writer.close();
}

From source file:org.kuali.ole.docstore.common.client.DocstoreRestClient.java

public File createZipFile(File sourceDir) throws IOException {
    File zipFile = File.createTempFile("tmp", ".zip");
    String path = sourceDir.getAbsolutePath();
    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile));
    ArrayList<File> fileList = getAllFilesList(sourceDir);
    for (File file : fileList) {
        ZipEntry ze = new ZipEntry(file.getAbsolutePath().substring(path.length() + 1));
        zip.putNextEntry(ze);//www.ja v  a 2s.co m
        FileInputStream fis = new FileInputStream(file);
        org.apache.commons.compress.utils.IOUtils.copy(fis, zip);
        fis.close();
        zip.closeEntry();
    }
    zip.close();
    return zipFile;
}

From source file:com.controlj.green.modstat.work.ModstatWork.java

@Override
public void run() {
    final ZipOutputStream zout;
    ByteArrayOutputStream out = new ByteArrayOutputStream(10000);
    zout = new ZipOutputStream(out);

    try {//  w ww  .  j  a  v  a 2  s.c o m

        connection.runReadAction(FieldAccessFactory.newFieldAccess(), new ReadAction() {

            public void execute(@NotNull SystemAccess access) throws Exception {
                Location root = access.getTree(SystemTree.Network).resolve(rootPath);

                Collection<ModuleStatus> aspects = root.find(ModuleStatus.class, Acceptors.acceptAll());

                synchronized (this) {
                    progressLimit = aspects.size();
                }

                for (ModuleStatus aspect : aspects) {
                    Location location = aspect.getLocation();
                    try {
                        if (!location.getAspect(Device.class).isOutOfService()) {
                            String path = getReferencePath(location);

                            //System.out.println("Gathering modstat from "+path);

                            ZipEntry entry = new ZipEntry(path + ".txt");
                            entry.setMethod(ZipEntry.DEFLATED);
                            zout.putNextEntry(entry);
                            IOUtils.copy(new StringReader(aspect.getReportText()), zout);
                            zout.closeEntry();

                            synchronized (this) {
                                progress++;
                                if (isInterrupted()) {
                                    error = new Exception("Gathering Modstats interrupted");
                                    return;
                                }
                            }
                        }
                    } catch (NoSuchAspectException e) { // skip and go to the next one
                    }
                }

            }
        });
    } catch (Exception e) {
        synchronized (this) {
            error = e;
        }
        return;
    } finally {
        try {
            zout.close();
        } catch (IOException e) {
        } // we tried our best
    }
    if (!hasError()) {
        cache = out.toByteArray();
    }
}

From source file:org.messic.server.api.APIPlayLists.java

@Transactional
public void getPlaylistZip(User user, Long playlistSid, OutputStream os)
        throws IOException, SidNotFoundMessicException {
    MDOPlaylist mdoplaylist = daoPlaylist.get(user.getLogin(), playlistSid);
    if (mdoplaylist == null) {
        throw new SidNotFoundMessicException();
    }//from  w w w. j ava2 s  .com
    List<MDOSong> desiredSongs = mdoplaylist.getSongs();

    ZipOutputStream zos = new ZipOutputStream(os);
    // level - the compression level (0-9)
    zos.setLevel(9);

    HashMap<String, String> songs = new HashMap<String, String>();

    M3U m3u = new M3U();
    m3u.setExtensionM3U(true);
    List<Resource> resources = m3u.getResources();

    for (MDOSong song : desiredSongs) {
        if (song != null) {

            // add file
            // extract the relative name for entry purpose
            String entryName = song.getLocation();
            if (songs.get(entryName) == null) {
                Resource r = new Resource();
                r.setLocation(song.getLocation());
                r.setName(song.getName());
                resources.add(r);

                songs.put(entryName, "ok");
                // song not repeated
                ZipEntry ze = new ZipEntry(entryName);
                zos.putNextEntry(ze);
                FileInputStream in = new FileInputStream(song.calculateAbsolutePath(daoSettings.getSettings()));
                int len;
                byte buffer[] = new byte[1024];
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
                in.close();
                zos.closeEntry();
            }
        }
    }

    // the last is the playlist m3u
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        m3u.writeTo(baos, "UTF8");
        // song not repeated
        ZipEntry ze = new ZipEntry(mdoplaylist.getName() + ".m3u");
        zos.putNextEntry(ze);
        byte[] bytes = baos.toByteArray();
        zos.write(bytes, 0, bytes.length);
        zos.closeEntry();
    } catch (Exception e) {
        e.printStackTrace();
    }

    zos.close();
}

From source file:com.hichinaschool.flashcards.libanki.Media.java

/**
 * Add files to a zip until over SYNC_ZIP_SIZE. Return zip data.
 * /*from   ww w . j a va  2  s.c o  m*/
 * @return Returns a tuple with two objects. The first one is the zip file contents, the second a list with the
 *         filenames of the files inside the zip.
 */
public Pair<File, List<String>> zipAdded() {
    File f = new File(mCol.getPath().replaceFirst("collection\\.anki2$", "tmpSyncToServer.zip"));

    String sql = "select fname from log where type = " + Integer.toString(MEDIA_ADD);
    List<String> filenames = mMediaDb.queryColumn(String.class, sql, 0);
    List<String> fnames = new ArrayList<String>();

    try {
        ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
        zos.setLevel(8);

        JSONObject files = new JSONObject();
        int cnt = 0;
        long sz = 0;
        byte buffer[] = new byte[2048];
        boolean finished = true;
        for (String fname : filenames) {
            fnames.add(fname);
            File file = new File(getDir(), fname);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file), 2048);
            ZipEntry entry = new ZipEntry(Integer.toString(cnt));
            zos.putNextEntry(entry);
            int count = 0;
            while ((count = bis.read(buffer, 0, 2048)) != -1) {
                zos.write(buffer, 0, count);
            }
            zos.closeEntry();
            bis.close();
            files.put(Integer.toString(cnt), fname);
            sz += file.length();
            if (sz > SYNC_ZIP_SIZE) {
                finished = false;
                break;
            }
            cnt += 1;
        }
        if (finished) {
            zos.putNextEntry(new ZipEntry("_finished"));
            zos.closeEntry();
        }
        zos.putNextEntry(new ZipEntry("_meta"));
        zos.write(Utils.jsonToString(files).getBytes());
        zos.close();
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }

    return new Pair<File, List<String>>(f, fnames);
}

From source file:com.zimbra.cs.zimlet.ZimletUtil.java

private static void addZipEntry(ZipOutputStream out, File file, String path) throws IOException {
    String name = (path == null) ? file.getName() : path + "/" + file.getName();
    if (file.isDirectory()) {
        for (File f : file.listFiles()) {
            addZipEntry(out, f, name);//  ww w  .  ja  va2  s .  c  o m
        }
        return;
    }
    ZipEntry entry = new ZipEntry(name);
    entry.setMethod(ZipEntry.STORED);
    entry.setSize(file.length());
    entry.setCompressedSize(file.length());
    entry.setCrc(computeCRC32(file));
    out.putNextEntry(entry);
    ByteUtil.copy(new FileInputStream(file), true, out, false);
    out.closeEntry();
}

From source file:info.novatec.inspectit.rcp.storage.util.DataRetriever.java

/**
 * Downloads and saves locally wanted files associated with given {@link StorageData}. Files
 * will be saved in passed directory. The caller can specify the type of the files to download
 * by passing the proper {@link StorageFileType}s to the method.
 * /*ww w  .j  a  va2  s .  c  om*/
 * @param cmrRepositoryDefinition
 *            {@link CmrRepositoryDefinition}.
 * @param storageData
 *            {@link StorageData}.
 * @param zos
 *            {@link ZipOutputStream} to place files to.
 * @param compressBefore
 *            Should data files be compressed on the fly before sent.
 * @param decompressContent
 *            If the useGzipCompression is <code>true</code>, this parameter will define if the
 *            received content will be de-compressed. If false is passed content will be saved
 *            to file in the same format as received, but the path of the file will be altered
 *            with additional '.gzip' extension at the end.
 * @param subMonitor
 *            {@link SubMonitor} for process reporting.
 * @param fileTypes
 *            Files that should be downloaded.
 * @throws BusinessException
 *             If directory to save does not exists. If files wanted can not be found on the
 *             server.
 * @throws IOException
 *             If {@link IOException} occurs.
 */
public void downloadAndZipStorageFiles(CmrRepositoryDefinition cmrRepositoryDefinition, StorageData storageData,
        final ZipOutputStream zos, boolean compressBefore, boolean decompressContent, SubMonitor subMonitor,
        StorageFileType... fileTypes) throws BusinessException, IOException {
    Map<String, Long> allFiles = getFilesFromCmr(cmrRepositoryDefinition, storageData, fileTypes);

    PostDownloadRunnable postDownloadRunnable = new PostDownloadRunnable() {
        @Override
        public void process(InputStream content, String fileName) throws IOException {
            String[] splittedFileName = fileName.split("/");
            String originalFileName = splittedFileName[splittedFileName.length - 1];
            ZipEntry zipEntry = new ZipEntry(originalFileName);
            zos.putNextEntry(zipEntry);
            IOUtils.copy(content, zos);
            zos.closeEntry();
        }
    };
    this.downloadAndSaveObjects(cmrRepositoryDefinition, allFiles, postDownloadRunnable, compressBefore,
            decompressContent, subMonitor);
}

From source file:fr.smile.alfresco.module.panier.scripts.SmilePanierExportZipWebScript.java

@Override
public void execute(WebScriptRequest request, WebScriptResponse res) throws IOException {

    String userName = AuthenticationUtil.getFullyAuthenticatedUser();

    PersonService personService = services.getPersonService();

    NodeRef userNodeRef = personService.getPerson(userName);

    MimetypeService mimetypeService = services.getMimetypeService();
    FileFolderService fileFolderService = services.getFileFolderService();

    Charset archiveEncoding = Charset.forName("ISO-8859-1");

    String encoding = request.getParameter("encoding");

    if (StringUtils.isNotEmpty(encoding)) {
        archiveEncoding = Charset.forName(encoding);
    }//from   w ww  .j  a  v  a 2s .c om

    ZipOutputStream fileZip = new ZipOutputStream(res.getOutputStream(), archiveEncoding);
    String folderName = "mon_panier";
    try {

        String zipFileExtension = "." + mimetypeService.getExtension(MimetypeMap.MIMETYPE_ZIP);

        res.setContentType(MimetypeMap.MIMETYPE_ZIP);

        res.setHeader("Content-Transfer-Encoding", "binary");
        res.addHeader("Content-Disposition",
                "attachment;filename=\"" + normalizeZipFileName(folderName) + zipFileExtension + "\"");

        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "public");
        res.setHeader("Expires", "0");

        fileZip.setMethod(ZipOutputStream.DEFLATED);
        fileZip.setLevel(Deflater.BEST_COMPRESSION);

        String archiveRootPath = folderName + "/";

        List<NodeRef> list = smilePanierService.getSelection(userNodeRef);
        List<FileInfo> filesInfos = new ArrayList<FileInfo>();
        for (int i = 0; i < list.size(); i++) {
            FileInfo fileInfo = fileFolderService.getFileInfo(list.get(i));
            filesInfos.add(fileInfo);
        }

        for (FileInfo file : filesInfos) {
            addEntry(file, fileZip, archiveRootPath);
        }
        fileZip.closeEntry();

    } catch (Exception e) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Erreur exportation Zip", e);
    } finally {
        fileZip.close();
    }

}