简体   繁体   English

在这种情况下,如何在 createNewFile() 期间发生 FileNotFoundException?

[英]How can FileNotFoundException occur during createNewFile() in this case?

Here is an attempt to write to external storage on my device:这是在我的设备上写入外部存储的尝试:

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();
        }
    }
}

A FileNotFoundException is thrown when trying to create the FileOutputStream.尝试创建 FileOutputStream 时抛出 FileNotFoundException。 I want to see the value of newDirsSuccess, but it does not show up in the debugger window so I'm not sure where this exception is coming from.我想查看 newDirsSuccess 的值,但它没有显示在调试器窗口中,所以我不确定这个异常来自哪里。

The "newFile" declaration should have created a new empty file, and parentDir.makeDirs() should have created any directories leading up to this new file, so why is this exception being thrown? “newFile”声明应该已经创建了一个新的空文件,并且 parentDir.makeDirs() 应该已经创建了通向这个新文件的所有目录,那么为什么会抛出这个异常呢?

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

I lacked the permission to write to external storage.我没有写入外部存储的权限。 Add this to AndroidManifest.xml:将此添加到 AndroidManifest.xml:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM