亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在SD卡上自動創建目錄

如何在SD卡上自動創建目錄

白衣非少年 2019-08-15 15:09:28
如何在SD卡上自動創建目錄我正在嘗試將我的文件保存到以下位置,FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName); 但是我得到了異常java.io.FileNotFoundException但是,當我把路徑保存"/sdcard/"起來的時候?,F在我假設我無法以這種方式自動創建目錄。有人可以建議如何創建directory and sub-directory使用代碼嗎?
查看完整描述

3 回答

?
www說

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" />


查看完整回答
反對 回復 2019-08-15
?
largeQ

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;}


查看完整回答
反對 回復 2019-08-15
  • 3 回答
  • 0 關注
  • 554 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號