简体   繁体   中英

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. 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.

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?

parentDir looked like: "/storage/emulated/0/decompressed/game1_stats"

I lacked the permission to write to external storage. Add this to AndroidManifest.xml:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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