Search code examples
androidutf-8unzip

Android - Unable to unzip downloaded zip file - UTFDataFormatException


I'm currently developing an android application in which I've to download a .zip archive and then unzip it. The download of the archive is done correctly. I'm able to unzip it manually directly on the phone or on my computer.

However, when I try to unzip programmatically the archive, I get a UTFDataFormatException. I tried to force the system encoding by adding :

System.setProperty("file.encoding", "UTF-8");

Or to process the names of the files :

filename = new String(ze.getName().getBytes("UTF-8"));

Did I miss something in my unzip function ?

private boolean unzip(String path, String zipname)
{
    InputStream is;
    ZipInputStream zis;

    try
    {
        String filename;
        is = new FileInputStream(path + zipname);
        zis = new ZipInputStream(new BufferedInputStream(is));
        ZipEntry ze;
        byte[] buffer = new byte[4096];
        int count;

        while ((ze = zis.getNextEntry()) != null)
        {
            filename = ze.getName();

            if (ze.isDirectory())
            {
                File fmd = new File(path + filename);
                fmd.mkdirs();
                continue;
            }

            FileOutputStream fout = new FileOutputStream(path + filename);

            while ((count = zis.read(buffer)) != -1)
            {
                fout.write(buffer, 0, count);
            }

            fout.close();
            zis.closeEntry();
        }

        zis.close();
    }
    catch(IOException e)
    {
        e.printStackTrace();
        return false;
    }

    return true;
}

Below the message of the exception :

java.io.UTFDataFormatException: bad byte at 72

Solution

  • After all, I used Zip4j library and it works very well. It's an old library which is not maintained and not callable thanks to gradle, but it fix my problem (http://www.lingala.net/zip4j/).

    try
    {
        ZipFile zipFile = new ZipFile(sourceFile);
        zipFile.extractAll(destinationPath);
    }
    catch (ZipException e)
    {
        e.printStackTrace();
    }