从SD卡解压缩文件

时间:2015-03-25 11:01:50

标签: java android

我正在尝试使用以下代码从sdcard解压缩文件

public void unzip(String zipFilePath, String destDirectory, String filename) throws IOException {

    File destDir = new File(destDirectory);
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry entry = zipIn.getNextEntry();
           // iterates over entries in the zip file
        while (entry != null) {
            String filePath = destDirectory + File.separator + entry.getName();              

                 if (!entry.isDirectory()) {                        
                        // if the entry is a file, extracts it
                        extractFile(zipIn, filePath);
                    } else {
                        // if the entry is a directory, make the directory                      ;
                        File dir = new File(filename);
                        dir.mkdir();
                    }
                    zipIn.closeEntry();
                    entry = zipIn.getNextEntry();
                }
                zipIn.close();
            }
            /**
             * Extracts a zip entry (file entry)
             * @param zipIn
             * @param filePath
             * @throws IOException
             */
            private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
                byte[] bytesIn = new byte[BUFFER_SIZE];
                int read = 0;
                while ((read = zipIn.read(bytesIn)) != -1) {
                    bos.write(bytesIn, 0, read);
                }
                bos.close();
            }

上面的代码给了我错误。以下是日志

java.io.FileNotFoundException: /mnt/sdcard/unZipedFiles/myfile/tt/images.jpg: open failed: ENOENT (No such file or directory)  

这里我ziped目录,其中包含images /子目录,然后我试图解压缩。

有人可以告诉我原因

由于

1 个答案:

答案 0 :(得分:1)

您正在尝试将文件写入不存在的目录。这不行。在unZIPping时,您不仅需要创建文件,还需要创建目录

将以下内容添加到extractPath()作为其开头行:

filePath.getParentFile().mkdirs();

这将获取应包含所需文件(filePath.getParentFile())的目录,然后创建所有必需的子目录(mkdirs())。

相关问题