Android Zip Entry Add addToArchive(String source, String target, String entryName)

Here you can find the source of addToArchive(String source, String target, String entryName)

Description

add To Archive

Declaration

public static void addToArchive(String source, String target,
            String entryName) throws IOException 

Method Source Code

//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;

import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class Main {
    public static void addToArchive(String source, String target,
            String entryName) throws IOException {

        File zip = new File(source);
        File tempFile = File.createTempFile(zip.getName(), null);
        tempFile.delete();/*from  www. j a  v a  2 s.  c o m*/
        if (!zip.renameTo(tempFile)) {
            throw new RuntimeException("could not rename the file "
                    + zip.getAbsolutePath() + " to "
                    + tempFile.getAbsolutePath());
        }

        byte[] buffer = new byte[32 * 1024];

        ZipInputStream zin = new ZipInputStream(new FileInputStream(
                tempFile));
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zip));

        {
            ZipEntry entry = zin.getNextEntry();
            while (entry != null) {
                String name = entry.getName();
                if (!name.equals(entryName)) {
                    out.putNextEntry(new ZipEntry(name));
                    int bytesRead;
                    while ((bytesRead = zin.read(buffer)) != -1) {
                        out.write(buffer, 0, bytesRead);
                    }
                }
                out.flush();
                out.closeEntry();
                entry = zin.getNextEntry();
            }
            zin.close();
        }

        {
            InputStream in = new FileInputStream(target);
            out.putNextEntry(new ZipEntry(entryName));
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
            out.closeEntry();
            in.close();
        }

        out.finish();
        out.close();

        tempFile.delete();
    }
}

Related

  1. saveEntry(String destPath, ZipEntry target, ZipFile zf)