1

As a disclaimer, I've already seen this post and the posts linking to it.

I have a file hosted on a server that is n archived file and I am trying to unarchive it using this method. When the file is pre-downloaded to the device and I open and unarchive it in my application, through an intent-filter from Downloads, there isn't any problem. However, when I download it from the server within my application, then try to unzip it, I get the error in the title on this line:

ZipFile zipfile = new ZipFile(archive);

Where archive is a File pointing to the archive file I downloaded. The code I'm using to download the archive is as follows:

    String urlPath = parameters[0], localPath = parameters[1];

    try
    {
        URL url = new URL(urlPath);
        URLConnection connection = url.openConnection();
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        int fileLength = connection.getContentLength();

        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new BufferedOutputStream(new FileOutputStream(localPath));

        byte data[] = new byte[1024];
        long total = 0;
        int count;

        while((count = input.read(data)) != -1)
        {
            total += count;
            publishProgress((int)total * 100 / fileLength);
            output.write(data);
        }

        output.flush();
        output.close();
        input.close();

I've recently added the encoding type as-per the post I referenced at the top, but I am still getting the same error. Any help would be great.

Just to clarify:

  • I have an archive file
  • It unarchives fine when the file was downloaded externally and opened/unarchived inside my app
  • When I download the archive and then try to unarchive it, I receive the error java.util.zip.ZipException: Central Directory Entry not found

My best guess is that this is a problem with my download. However, that being said, I don't know what I'm doing wrong.

Community
  • 1
  • 1
RileyE
  • 10,874
  • 13
  • 63
  • 106

1 Answers1

5

You aren't copying the download correctly. You must use

output.write(data, 0, count);

Otherwise you are writing arbitrary junk into the file.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Really? The docs say that `write(buffer)` is `Equivalent to write(buffer, 0, buffer.length).` – RileyE Feb 01 '13 at 23:48
  • @RileyE Of course it is, but neither is equivalent to the code I posted. You need to go and read the documentation for read(). – user207421 Feb 02 '13 at 00:05
  • Oh right. I noticed that it wasn't reading the full byte size. I don't know how I didn't catch that. Good point. Thank you good sir! – RileyE Feb 02 '13 at 03:30