java - 如何在android中解压带有子目录的文件?

标签 java android io unzip

当我解压文件时,它的文件名类似于Movies\Hollywood\spider-Man。 实际上电影是一个文件夹,好莱坞是电影中的文件夹,蜘蛛侠是好莱坞中的文件。

最佳答案

如果在创建 zip 时Movies\Hollywood\spider-Man 是一个文件,则无论其是否具有扩展名(例如 *.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。

关于java - 如何在android中解压带有子目录的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43672241/

相关文章:

java - HttpClient POST 获取 html 页面的速度比浏览器慢约 2.5 倍

java - 将已排序 ArrayList 中的重复项分组到另一个 ArrayList 中

android - 播放歌曲时 MediaController 播放按钮未更新

python - 转换代码以在windows中读取文件到linux

java - SimpleAdapter 不在 GUI 上显示数据

android - 在 ChildItem 中单击按钮时折叠 ExpandableListView GroupItem

android - Flex/Actionscript拖放/滑动效果(模拟android/ios界面)

design-patterns - Haskell IO 输出不正确

java - 如何在java中对 "\"进行字符串分割?

java - 为什么大括号后不需要分号?