【问题标题】:How can FileNotFoundException occur during createNewFile() in this case?在这种情况下,在 createNewFile() 期间如何发生 FileNotFoundException?
【发布时间】:2016-05-02 00:50:45
【问题描述】:

这是我设备上写入外部存储的尝试:

private void extract(ZipInputStream zis) throws IOException {
    ZipEntry entry;
    while((entry = zis.getNextEntry()) != null) {
        if(!entry.isDirectory()) {
            writeFile(zis, entry.getName());
        }
        zis.closeEntry();
    }
    zis.close();
}

private void writeFile(ZipInputStream zis, String filename) {
    /* flag to determine if creation of every directory leading to
     * filename was successful */
    boolean newDirsSuccess;
       if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        BufferedOutputStream bos = null;
        try {
            File newFile = new File(Environment.getExternalStorageDirectory(),
                    "decrompressed/" + filename);
            // ignore special files
if(newFile.getName().equals(".DS_Store")||newFile.getAbsolutePath().contains("__") ) {
                return;
            }

            File parentDir = newFile.getParentFile();
            // if the file's parent structure isn't there, create it
            if (!parentDir.exists()) {
                newDirsSuccess = parentDir.mkdirs();
            }

            // this line throws a FileNotFoundException NOENT
            FileOutputStream fos = new FileOutputStream(newFile);
            bos = new BufferedOutputStream(fos);

            byte[] byteArr = new byte[4096];
            int numBytes = 0;

            // read from ZipInputStream and rite the bytes
            while((numBytes = zis.read(byteArr)) != -1) {
                bos.write(byteBuffer, 0, numBytes);
            }
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

尝试创建 FileOutputStream 时抛出 FileNotFoundException。我想查看 newDirsSuccess 的值,但它没有显示在调试器窗口中,所以我不确定这个异常来自哪里。

“newFile”声明应该创建了一个新的空文件,并且 parentDir.makeDirs() 应该创建了指向这个新文件的任何目录,那么为什么会抛出这个异常呢?

parentDir 看起来像:“/storage/emulated/0/decompressed/game1_stats”

【问题讨论】:

  • mkdirs() 是否返回 true
  • 你读过这个问题吗?
  • 是的,我确实阅读了这个问题,但在那里我没有看到答案。我还是没有。尽管您未能提供答案,但仍然需要答案。例如,您可以 打印 结果,或将其分配给更大范围内的变量。我还想知道为什么你的标题说当你不调用createNewFile() 时异常发生在createNewFile() 中(并且当createNewFile() 不抛出异常时,无论如何都是多余的)。无法回答包含并依赖于这么多猜测的问题。
  • “我想查看 newDirsSuccess 的值,但它没有显示在调试器窗口中,所以我不确定这个异常来自哪里。” newDirsSuccess 是说变量。 createNewFile 是我拥有的东西,直到我意识到它是多余的。

标签: java android file-io


【解决方案1】:

我没有写入外部存储的权限。将此添加到 AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

【讨论】:

    猜你喜欢
    • 2018-11-14
    • 2023-03-15
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 2012-03-22
    相关资源
    最近更新 更多