2013-07-09 56 views
3

我得到這個錯誤獲得FileNotFoundException異常/ EISDIR

java.io.FileNotFoundException: /data/data/com.example.app/cache/news.xml:打開失敗: EISDIR(是一個目錄)

使用此代碼

try { 
    File cache = ctx.getCacheDir(); 
    String s = cache.getAbsolutePath() + File.separator + path; 
    File f = new File(s); 
    File pf = f.getParentFile(); 
    if (pf != null) { 
    pf.mkdirs(); 
    } 
    if ((pf.exists()) && (pf.isDirectory())) {   
    if ((!f.exists()) || (!f.isFile())) { 
     f.createNewFile(); 
    } 
    if ((f.exists()) || (f.isFile())) { 
     FileOutputStream os = null;   
     os = new FileOutputStream(s, false);    
     if (os != null) { 
     SharedCode.sharedWriteTextFileToStream(str, os);     
     } 
     os.flush(); 
     os.close(); 
    } 
    } 
} 
catch (IOException e) { 
    String s = e.toString(); 
}   

更新添加代碼刪除與所需文件名匹配的目錄(f any)+正確使用mkdirs似乎解決了這個問題。接受最接近的答案。

+0

您是否聲明瞭'WRITE_EXTERNAL_STORAGE'權限? –

+0

的路徑是否包含文件名? – giorashc

+0

@giorasch是的它確實 – Tom

回答

9

mkdirs()不僅創建導致該文件的目錄,而且創建一個文件指向路徑的目錄。這就是爲什麼createNewFile()失敗。您需要在父文件上調用mkdirs()

File parent = f.getParentFile(); 
if (parent != null) parent.mkdirs(); 
+0

我已更改爲現在使用您的代碼。但我仍然得到同樣的錯誤。我會試着研究一下如果有一個目錄與我正在創建的文件具有相同的名稱,如果是,可能試圖先刪除它。 (Torgther與您的解決方案,這應該解決問題) – Tom

1

請注意

f.mkdirs(); 

你需要檢查該語句的返回值。如果是,則繼續,否則路徑不存在。

+0

儘管如此,但這並不能解決問題。 – giorashc

+0

@giorashc你對。我只是想方設法讓他自己找到正確的答案。這樣我們就不需要做勺子餵養 –

+0

我會添加代碼來檢查,但僅供參考,它是真的。 – Tom

相關問題