3 回答

TA貢獻1775條經驗 獲得超8個贊
如果您創建一個包裝頂級目錄的File對象,您可以調用它的mkdirs()方法來構建所有需要的目錄。就像是:
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
注意:使用Environment.getExternalStorageDirectory()來獲取“SD卡”目錄可能是明智之舉,因為如果手機出現了除SD卡以外的其他東西(例如內置閃存,則可能會更改)蘋果手機)。無論哪種方式,您都應該記住,您需要檢查以確保它實際存在,因為可能會移除SD卡。
更新:自API級別4(1.6)起,您還必須請求許可。這樣的事情(在清單中)應該有效:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

TA貢獻2039條經驗 獲得超8個贊
這對我有用。
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
在你的清單和下面的代碼中
public static boolean createDirIfNotExists(String path) { boolean ret = true; File file = new File(Environment.getExternalStorageDirectory(), path); if (!file.exists()) { if (!file.mkdirs()) { Log.e("TravellerLog :: ", "Problem creating Image folder"); ret = false; } } return ret;}
- 3 回答
- 0 關注
- 554 瀏覽
添加回答
舉報