Monday, October 25, 2010

Unzip files in Android

You need an app that can unzip files? Android provides the classes that are required for this. Basically you will need to checkout two classes. There are other related classes also which would help you with various other things.
  1. ZipInputStream
  2. ZipEntry
This example shows you how to unzip a zip file through these classes. If you want to create zip files, that's also possible, but we will keep it for later. In this project, there is a zip file, called ZipTest.zip in the assets folder. It's pretty easy to pick up any zip file on your phone through code. For simplicity, I have placed out test file in the assets folder.

The code is simple enough to need any more explanations. I have put comments in the code. So, do check it out and run it. I have logged the steps on the Activity. The output files are not readable yet in this example due to the format of writing that I have done here (Update: As per rekin's comment, this is fixed now). But you get idea about how to unzip those files. You can find the whole working code here.

Note: There's not much error handling code put in place.

4 comments:

  1. There is one major issue about your code.
    You can't do like this:
    while ((count = inputStream.read(data, 0, BUFFER)) != -1){
    bufferedOutputStream.write(data);}
    Why? Because when you read less bytes than BUFFER, you write rubbish data to your stream (because no matter if your data[] is full it will flush all it's content)
    So instead of line:
    bufferedOutputStream.write(data);
    use:
    bufferedOutputStream.write(data,0,count);
    And you write only that much data to stream, as much was really read.

    Cheers,
    rekin

    ReplyDelete
  2. @Rekin: Thanks for pointing that out. Indeed that was a mistake. I have updated the code now. :)

    ReplyDelete
  3. Hi , I am new to android development . I tried to run my sample application using your working code . I have put my zip file in Assets folder and entered its contents in InputStream , and now i am getting exception as "java.io.filenotfoundexception(No such file or directory) .I have checked t again but I am not able to get solution of this problem ..Your help is appreciated .

    ReplyDelete
  4. Your script worked for me. Thanks a lot for a big help. :)

    ReplyDelete