Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a ZIP file with Android

How can I create a ZIP file from an XML file?

I want to take a backup of all my inbox messages in XML, and compress the XML file and store it on an SD card.

like image 959
Vaibhav Vajani Avatar asked Sep 06 '26 04:09

Vaibhav Vajani


1 Answers

The following code solved my problem.

public class makeZip {
    static final int BUFFER = 2048;

    ZipOutputStream out;
    byte data[];

    public makeZip(String name) {
        FileOutputStream dest=null;
        try {
            dest = new FileOutputStream(name);
        } 
        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        out = new ZipOutputStream(new BufferedOutputStream(dest));
        data = new byte[BUFFER];
    }

    public void addZipFile (String name) {
        Log.v("addFile", "Adding: ");
        FileInputStream fi=null;
        try {
            fi = new FileInputStream(name);
            Log.v("addFile", "Adding: ");
        }
        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.v("atch", "Adding: ");
        }
        BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
        ZipEntry entry = new ZipEntry(name);
        try {
            out.putNextEntry(entry);
            Log.v("put", "Adding: ");
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int count;
        try {
            while((count = origin.read(data, 0, BUFFER)) != -1) {
               out.write(data, 0, count);
               //Log.v("Write", "Adding: "+origin.read(data, 0, BUFFER));
            }
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
             Log.v("catch", "Adding: ");
        }
        try {
            origin.close();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void closeZip () {
        try {
            out.close();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
like image 73
Vaibhav Vajani Avatar answered Sep 07 '26 18:09

Vaibhav Vajani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!