[英]FileNotFoundException on FileOutputStream in spite of mkdirs() and createNewFile()
[英]How can FileNotFoundException occur during createNewFile() in this case?
这是在我的设备上写入外部存储的尝试:
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”
我没有写入外部存储的权限。 将此添加到 AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.