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

时间:2016-05-02 00:50:46

标签: java android file-io

以下是尝试写入设备上的外部存储空间:

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”

1 个答案:

答案 0 :(得分:0)

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

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