2013-10-01 57 views
2

上失敗當我嘗試在應用程序內部存儲器下創建目錄結構時(例如/data/data/[pkgname]/x/y/z...),我看到幾次崩潰。在應用程序內部存儲器上的mkdirs()在我的應用程序中的Android

這裏是失敗的代碼:

File clusterDirectory = new File(MyApplication.getContext().getFilesDir(), "store"); 
File baseDirectory = new File(clusterDirectory, "data"); 
if (!baseDirectory.exists()) { 
    if (!baseDirectory.mkdirs()) { 
     throw new RuntimeException("Can't create the directory: " + baseDirectory); 
    } 
} 

我的代碼拋出試圖創建以下路徑時除外:

java.lang.RuntimeException: Can't create the directory: /data/data/my.app.pkgname/files/store/data 

我的清單指定權限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />,即使它不應該對此目的是必要的(由於Google Maps Android API v2,我的應用程序實際上是必需的)。

它似乎與手機沒有關係,因爲我在舊手機和新手機上都得到了這個例外(最新的崩潰報告是Android 4.3的Nexus 4)。

我的猜測是,目錄/data/data/my.app.pkgname首先不存在,但mkdirs()由於權限問題無法創建它,這可能嗎?

任何提示?

感謝

回答

4

使用getDir(String name, int mode)創建目錄到內部存儲器。方法根據需要檢索,創建應用程序可以放置自己的自定義數據文件的新目錄。您可以使用返回的File對象來創建和訪問此目錄中的文件。


因此例子是

// Create directory into internal memory; 
File mydir = context.getDir("mydir", Context.MODE_PRIVATE); 
// Get a file myfile within the dir mydir. 
File fileWithinMyDir = new File(mydir, "myfile"); 
// Use the stream as usual to write into the file. 
FileOutputStream out = new FileOutputStream(fileWithinMyDir); 

對於嵌套的目錄,你應該使用一般的Java方法。像

new File(parentDir, "childDir").mkdir(); 

所以更新的例子應該是

// Create directory into internal memory; 
File mydir = getDir("mydir", Context.MODE_PRIVATE); 

// Create sub-directory mysubdir 
File mySubDir = new File(mydir, "mysubdir"); 
mySubDir.mkdir(); 

// Get a file myfile within the dir mySubDir. 
File fileWithinMyDir = new File(mySubDir, "myfile"); 
// Use the stream as usual to write into the file. 
FileOutputStream out = new FileOutputStream(fileWithinMyDir); 
+0

謝謝,這是很好的在應用程序存儲創建目錄的第一級(在我的情況「存儲」),但什麼關於嵌套目錄?在第一級的返回文件上使用mkdirs()是否安全? – Venator85

+0

是的,你可以試試。 –

+0

@ Venator85查看我更新的答案。我添加了一個示例代碼來創建嵌套的目錄。 –

相關問題