2016-09-13 91 views
0

我的目標是在外部SD卡的給定目錄中的一個不存在的文件中寫入一些文本。不幸的是,我無法使用我的android應用程序在目錄中創建這樣的文件。
我發現了幾個適用於其他人的代碼示例,但它們不適用於我的應用程序。因此,任何建議都不勝感激。謝謝!在Android應用的外部SD卡上的現有目錄中創建文件

這裏是我的相關代碼:

1.清單

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


2. Java的類

FileOutputStream fos ; 
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { 
    try { 
     File sdCard = Environment.getExternalStorageDirectory(); 
     File file = new File(sdCard.getAbsolutePath() + File.separator + 
          "givenDirectory" + File.separator + "newFile"); 
     fos = new FileOutputStream(file); 
     String data = "some text"; 
     fos.write(data.getBytes()); 
     fos.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

我使用的Android版本5.1.1我移動電話。 java類的提取是靜態void的一部分,只包含帶引號的代碼。

問題:文件沒有創建

+0

「我的目標是寫在一個不存在的文件中的一些文本的外置SD卡上的指定目錄」 - 您的代碼是用於[外部存儲](https://commonsware.com/blog/2014/04/08/storage-situation-external-storage.html)。這不是[可移動存儲](https://commonsware.com/blog/2014/04/09/storage-situation-removable-storage.html)(我如何解釋「外部SD卡」)。除此之外,您應該查看LogCat以查找與異常處理程序關聯的任何Java堆棧跟蹤,並且應該使用'adb shell'來查看文件是否存在,因爲您沒有編制索引。 – CommonsWare

回答

相關問題