2015-06-28 102 views
0

我創建了一個需要在我的外部SD卡(extSdCard)上創建文件夾並寫入文本文件的Android應用程序。我正在使用Galaxy S4設備,併爲此寫下了以下代碼。我已經知道/ mnt/..文件的路徑併爲它創建了一個字符串。 android manifest.xml文件使用權限。我已經在Cmd提示符中檢查了「adb logcat」中的代碼,並且它不會給出任何錯誤,但不會創建任何文件夾。該設備也被檢查與PC不連接。希望你能幫助我。這是代碼。我無法寫入Android Studio中的外部SD卡(extSdCard)

String externalFilePath="/mnt/extSdCard/tmp"; 

      Log.d(TAG, "externalFilePath is: "+externalFilePath); 

      File myfile = new File(externalFilePath, "Hello"); 
+1

不要使用硬編碼路徑,並確保你有權限... <使用權限android:name =「android.permission.WRITE_EXTERNAL_STORAGE」/> – Proxytype

+0

你使用的是哪個版本的android? KitKat不允許這樣做,但是棒棒糖似乎已經把它帶回來了。 – user3711421

+0

我已經添加了權限。儘管可寫,但我可以在設備存儲中創建文件夾,但不能在SD卡上創建。你的意思是電話設備也有Kitkat或棒棒糖版本?我認爲這只是模擬器。 – iripilot

回答

1

試試這個代碼來生成您的應用程序包下的文件

File path = getExternalFilesDir(Environment.DIRECTORY_PICTURES); 

//你的需要更換DIRECTORY_PICTURES

File file = new File(path, "Hello"); 

還要確保您所添加的權限

+0

它不會給出錯誤,但仍然不會以此方式創建任何文件夾。我已經看到了環境選項而不是DIRECTORY_PICTURES,似乎他們將內部設備存儲稱爲下載,文檔等選項。 – iripilot

4

首先確保你的線內有manifest,xml ,在application標籤之外的某處。

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

然後,你可以寫一個File這樣做:

File sdcard = Environment.getExternalStorageDirectory(); 
File dir = new File(sdcard.getAbsolutePath() + "/tmp/"); 
// creates if doesn't exists 
dir.mkdir(); 
// create a File 
File file = new File(dir, "Example.txt"); 
FileOutputStream os = outStream = new FileOutputStream(file); 
//this is the text that will be inside of the Example.txt 
String data = "Hello world"; 
os.write(data.getBytes()); 
os.close(); 

希望它能幫助:)