0

我已经下载了 zip 文件,当我解压缩文件时,我得到了上述异常。以下是我解压缩 zip 文件后的结构。

zip结构(解压后):folder1 subfolder1 sub1 sub2 subfolder2 subf1 subf2

 String inputPath = Environment.getExternalStorageDirectory().getPath()+"/"+arrayListQuestions.get(0).getQuestion_asset_name();

            Log.e("inputPath",inputPath);
            String outputPath = Environment.getExternalStorageDirectory().getPath()+"/unzip/";
            Log.e("outPath",outputPath);
ZipManager zipManager = new ZipManager();
        try {
            zipManager.unzip(inputPath, outputPath);
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("error_unzip",e.getLocalizedMessage());
        }

UnzipFunction:

public void unzip(String zipFilePath, String destDirectory) throws IOException {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdir();
            }
        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(filePath);
                dir.mkdir();
                }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
            }
        zipIn.close();
        }


    private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] bytesIn = new byte[BUFFER];
        int read = 0;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
            }
        bos.close();
        }
4

1 回答 1

0

解决方案是使用ZipFile而不是ZipInputStream. ZipFile似乎可以优雅地处理无名本地文件头

注意ZipFile的缺点是不能处理任意InputStreams,只取文件。

另请注意,该问题似乎特定于 Android。Oracle 的 JRE 没有出现此异常。

于 2021-02-22T10:27:25.363 回答