2010-01-04 32 views
21

沒有讀/寫權限餘米使用的是Android 1.5我的數據目錄不具有讀/寫權限Data目錄在Android的

System.out.println("DAta can write??--->"+Environment.getDataDirectory().canWrite()); 
System.out.println("DAta can read??--->"+Environment.getDataDirectory().canRead()); 

所以,請建議我如何提供數據目錄的權限。

我想要做的就是創建一個文件,並添加一些內容,以在模擬器中的數據存儲像如下

private void writeToSDCard() { 
     try { 

      File lroot = Environment.getDataDirectory(); 

      if (lroot.canWrite()){ 
       File lfile = new File(lroot, "samplefile.txt"); 
       FileWriter lfilewriter = new FileWriter(lfile); 
       BufferedWriter lout = new BufferedWriter(lfilewriter); 
       lout.write("XXXXXXXXXXXXXXXXXX"); 
       lout.close(); 
      } 
     } catch (IOException e) { 
      Log.e(m_cTAG, "Could not write file " + e.getMessage()); 
     } 
    } 

回答

64

你不應該看的數據目錄。這是手機存儲中的系統目錄 - 通常爲/data - 並且您的應用程序永遠不會有寫入權限。

應用程序應該寫入文件的目錄由Context.getFilesDir() method返回。它會像/data/data/com.yourdomain.YourApp/files

如果要寫入手機存儲中的文件,請使用Context.openFileOutput() method

如果您想要SDCard的路徑,請使用Environment.getExternalStorageDirectory() method。寫信給你需要通過添加以下到您的清單,讓您的應用程序的適當的權限和SD卡:如果你要寫信給你還需要檢查它的狀態和SD卡

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

getExternalStorageState()方法。

如果你正在存儲與你的應用程序有關的小文件,那麼這些文件可能會進入手機的存儲空間,而不是SD卡,因此請使用Context.openFileOutput()Context.openFileInput()方法。

在你的代碼

所以考慮是這樣的:

OutputStream os = openFileOutput("samplefile.txt", MODE_PRIVATE); 
BufferedWriter lout = new BufferedWriter(new OutputStreamWriter(os)); 
+0

這裏是Wat米tryng做: 私人無效writeToSDCard(){ 嘗試{ \t文件lroot = Environment.getDataDirectory(); (lroot.canWrite()){ \t \t if(lroot.canWrite()){ \t File lfile = new File(lroot,「samplefile.txt」); \t FileWriter lfilewriter = new FileWriter(lfile); \t BufferedWriter lout = new BufferedWriter(lfilewriter); \t lout.write(「XXXXXXXXXXXXXXXXXX」); \t lout.close(); (m_cTAG,「Could not write file」+ e.getMessage()); \t} } – 2010-01-04 10:01:08

+0

是啊感謝您的寶貴意見.. :-) – 2010-01-04 10:13:07

+0

謝謝你解決了我的問題。 – specialscope 2013-12-03 04:53:29

相關問題