[英]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.