2012-10-10 60 views
2

我有一個應用程序可以創建一個配置文件和一個日誌文件。我將它們存儲在外部存儲器中,但是當我在我的android模擬器中嘗試時,它不起作用,因爲外部存儲器不可寫。如果發生這種情況,我應該在哪裏存儲文件?我應該在Android中存儲文件?

這是我的代碼:

private void createConfigurationFile(){ 
    File ssConfigDirectory = 
     new File(Environment.getExternalStorageDirectory()+"/MyApp/config/"); 
    File file = new File(ssConfigDirectory, mUsername+".cfg"); 

    if(!file.exists()){ 
     try{ 
      String state = Environment.getExternalStorageState(); 
      if (!Environment.MEDIA_MOUNTED.equals(state)){ 
       ssConfigDirectory = new File("PATH_WHERE_I_SHOULD_STORE_IT"); 
      } 
      File ssLogDirectory = new File(ssConfigDirectory+"/SweetSyncal/log/"); 
      ssLogDirectory.mkdirs();     
      ssConfigDirectory.mkdirs(); 

      File outputFile = new File(ssConfigDirectory, mUsername+".cfg");     
      FileOutputStream fOut = new FileOutputStream(outputFile); 
      OutputStreamWriter osw = new OutputStreamWriter(fOut); 

      writeFile(osw); 
      osw.flush(); 
      osw.close(); 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
    } 
} 
+0

你有寫權限到外部存儲? –

+0

在我的清單中我做了,但外部存儲狀態不是MEDIA_MOUNTED,所以我不能在那裏寫。在我的真實設備中,它工作正常。 –

回答

3

如果文件不是太大,你可以將其保存在設備的內部存儲。

訪問內部存儲,您可以使用以下方法:

FileOutputStream openFileOutput (String name, int mode)

(您需要的Context的情況下使用它)

例子:

String FILENAME = "hello_file"; 
String string = "hello world!"; 

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
fos.write(string.getBytes()); 
fos.close(); 

由於爲什麼你提供的代碼不工作,那麼有兩種可能性:

  1. 您忘了添加必需的權限(WRITE_EXTERNAL_STORAGE)。
  2. 您的模擬器沒有啓用SD卡。假設你正在使用Eclipse,你可以在AVD管理器中啓用它。只需編輯您的AVD實例,並在相應的字段中輸入SD卡的大小。您還應該添加名爲SD Card Support的硬件功能並將其設置爲TRUE。

在官方開發者指南中有一篇很棒的文章,它會告訴你一切你需要知道的關於Android存儲的知識。

可以讀取它HERE

相關問題