如何解压缩android中的子目录文件?

时间:2017-04-28 04:56:27

标签: java android io unzip

当我解压缩file.it的文件名像Movies \ Hollywood \ spider-Man。 实际上电影是一个文件夹,好莱坞是电影中的文件夹,蜘蛛侠是好莱坞的文件。

1 个答案:

答案 0 :(得分:2)

如果 Movies \ Hollywood \ spider-Man 是创建zip时的文件,则应将其解压缩为文件,无论是否具有扩展名(如* .mp4,* .flv)

您可以依赖命名空间java.util.zip下的java API,文档链接是here

编写一些只提取zip文件的代码,它应该将文件条目提取为文件(不支持gzip,rar)。

private boolean extractFolder(File destination, File zipFile) throws ZipException, IOException
{
    int BUFFER = 8192;
    File file = zipFile;
    //This can throw ZipException if file is not valid zip archive
    ZipFile zip = new ZipFile(file);
    String newPath = destination.getAbsolutePath() + File.separator + FilenameUtils.removeExtension(zipFile.getName());
    //Create destination directory
    new File(newPath).mkdir();
    Enumeration zipFileEntries = zip.entries();

    //Iterate overall zip file entries
    while (zipFileEntries.hasMoreElements())
    {
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
        String currentEntry = entry.getName();
        File destFile = new File(newPath, currentEntry);
        File destinationParent = destFile.getParentFile();
        //If entry is directory create sub directory on file system
        destinationParent.mkdirs();

        if (!entry.isDirectory())
        {
            //Copy over data into destination file
            BufferedInputStream is = new BufferedInputStream(zip
            .getInputStream(entry));
            int currentByte;
            byte data[] = new byte[BUFFER];
            //orthodox way of copying file data using streams
            FileOutputStream fos = new FileOutputStream(destFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, currentByte);
            }
            dest.flush();
            dest.close();
            is.close();
        }
    }
    return true;//some error codes etc.
}

例程不执行任何异常处理,请在驱动程序代码中捕获ZipException和IOException。