在ExternalFilesDir中获取随机的mkdirs故障

时间:2019-05-31 12:49:11

标签: java android mkdirs

我正在尝试在getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)中解压缩文件夹。一些用户很少有解压缩随机子文件夹的错误。在成功解压缩了zip的其他子文件夹之后,就会发生这种情况,因此对我而言这没有意义。

清单中已经有android.permission.WRITE_EXTERNAL_STORAGE,尽管自Kitkat以来,该目录不是必需的权限。

private Boolean unzipFile(String zipFilePath) throws ObservableException {
        File destinationDir = new File(zipFilePath.substring(0, zipFilePath.lastIndexOf(".")));

        try (ZipFile zip = new ZipFile(zipFilePath)) {
            if (!destinationDir.exists() && !destinationDir.mkdirs()) {
                throw new ObservableException(" destination root folder could not be created and ");
            }
            Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
            while (zipFileEntries.hasMoreElements()) {
                ZipEntry entry = zipFileEntries.nextElement();
                String entryName = entry.getName();
                File destFile = new File(destinationDir, entryName);
                File destinationParent = destFile.getParentFile();
                createDir(destinationParent);
                if (!destinationParent.canWrite()) {
                    throw new ObservableException("cannot write in this directory");
                }
                if (!entry.isDirectory()) {
                    extractFile(zip, entry, destFile);
                } else {
                    File dir = new File(destFile.getAbsolutePath());
                    createDir(dir);
                }
            }
        } catch (Exception e) {
        ...
        } finally {
            File zipFile = new File(zipFilePath);
            if (zipFile.delete()) {
                Log.d(TAG, zipFilePath + " deleted");
            }
        }
        return true;
    }


    private void createDir(File path) throws ObservableException, IOException {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createDirectories(Paths.get(path.getPath()));
        } else {
            if (!path.exists() && !path.mkdirs()) {
                throw new ObservableException(" folder could not be created");
            }
        }
    }

在createDir()中,if(!path.exists()&&!path.mkdirs())子句有时为true,这会导致错误。

0 个答案:

没有答案