2010-01-25 92 views
171

上自動創建目錄我想我的文件保存到以下位置
FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName); ,但我發現異常java.io.FileNotFoundException
然而,當我把路徑"/sdcard/"它的工作原理。如何SD卡

現在我假設我無法以這種方式自動創建目錄。

有人可以建議如何使用代碼創建一個directory and sub-directory

回答

422

如果您創建一個包含頂級目錄的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); 

注:如果一個電話走來具有比SD卡以外的東西(如建這可能是明智的使用Environment.getExternalStorageDirectory()爲獲得「SD卡」目錄,因爲這可能會改變在閃光,a'la iPhone)。無論哪種方式,你應該記住,你需要檢查,以確保它實際上存在,因爲SD卡可能被刪除。

更新:由於API級別4(1.6),您還必須申請許可。像這樣的東西(在清單)應該工作:

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

感謝fixXedd。它工作完美。 – 2010-01-25 09:09:40

+2

沒問題。樂於幫助。 – 2010-01-25 23:39:09

+1

是的,隨後發佈的三星平板電腦使用內置閃存 – CQM 2011-09-14 17:08:02

57

有同樣的問題,只是想補充一點,AndroidManifest.xml中也需要該權限:

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

隨着API 8和越大, SD卡的位置已更改。 @ fiXedd的答案很好,但對於更安全的代碼,您應該使用Environment.getExternalStorageState()來檢查媒體是否可用。然後,您可以使用getExternalFilesDir()導航到您想要的目錄(假設您使用API​​ 8或更高版本)。

你可以在SDK documentation瞭解更多。

38

這是對我有用的東西。

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

我應該如何傳遞地址?作爲「folderPath」或「/ folderPath」? – 2013-10-09 10:30:26

+0

path是要創建的文件夾的名稱。如果您發送了像MusicDownload這樣的路徑,它會自動變爲/ sdcard/MusicDownload。 Shajeel Afzal – shehzy 2015-07-08 06:49:33

+0

它拋出異常java.io.IOException:打開失敗:ENOENT(沒有這樣的文件或目錄) – 2017-12-03 17:19:48

5

代碼我面臨同樣的問題,無法創建於Galaxy S的目錄,但能在Nexus和三星Droid的成功創建。我如何固定它是通過添加代碼下面一行:

File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/"); 
dir.mkdirs(); 
8

確保外部存儲存在: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

private boolean isExternalStoragePresent() { 

     boolean mExternalStorageAvailable = false; 
     boolean mExternalStorageWriteable = false; 
     String state = Environment.getExternalStorageState(); 

     if (Environment.MEDIA_MOUNTED.equals(state)) { 
      // We can read and write the media 
      mExternalStorageAvailable = mExternalStorageWriteable = true; 
     } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 
      // We can only read the media 
      mExternalStorageAvailable = true; 
      mExternalStorageWriteable = false; 
     } else { 
      // Something else is wrong. It may be one of many other states, but 
      // all we need 
      // to know is we can neither read nor write 
      mExternalStorageAvailable = mExternalStorageWriteable = false; 
     } 
     if (!((mExternalStorageAvailable) && (mExternalStorageWriteable))) { 
      Toast.makeText(context, "SD card not present", Toast.LENGTH_LONG) 
        .show(); 

     } 
     return (mExternalStorageAvailable) && (mExternalStorageWriteable); 
    } 
21

其實我用@fiXedd asnwer的一部分,它爲我工作:

//Create Folder 
    File folder = new File(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images"); 
    folder.mkdirs(); 

    //Save the path as a string value 
    String extStorageDirectory = folder.toString(); 

    //Create New file and name it Image2.PNG 
    File file = new File(extStorageDirectory, "Image2.PNG"); 

確保您使用的mkdirs()不MKDIR()創建的完整路徑

+0

@fixedd答案的這個「部分」是什麼?他的回答是使用'File.mkdirs()'。然後他展示了一個使用它的例子。 – Doomsknight 2012-09-07 15:15:17

+0

其實我不記得有什麼區別,但我認爲有一些編輯...順便提及,我用他的答案獲得解決方案 – Amt87 2013-07-15 08:23:11

5

不要忘記確保文件/文件夾名稱中沒有特殊字符。發生在我身上用 「:」 當我使用變量(一個或多個)

設置文件夾的名稱不允許在文件/文件夾名稱的字符

「* /?:<> \ |

U可以找到這個代碼在這種情況下有益的

下面的代碼刪除所有「:」,並以替換它們「 - 」

//actualFileName = "qwerty:asdfg:zxcvb" say... 

    String[] tempFileNames; 
    String tempFileName =""; 
    String delimiter = ":"; 
    tempFileNames = actualFileName.split(delimiter); 
    tempFileName = tempFileNames[0]; 
    for (int j = 1; j < tempFileNames.length; j++){ 
     tempFileName = tempFileName+" - "+tempFileNames[j]; 
    } 
    File file = new File(Environment.getExternalStorageDirectory(), "/MyApp/"+ tempFileName+ "/"); 
    if (!file.exists()) { 
     if (!file.mkdirs()) { 
     Log.e("TravellerLog :: ", "Problem creating Image folder"); 
     } 
    } 
+0

+1亞我也嘗試過:並得到錯誤,最後找到該問題和刪除:以及所有其他特殊字符。 – 2013-07-15 05:49:09

1

您可以使用/ SD卡的/不是Environment.getExternalStorageDirectory()

private static String DB_PATH = "/sdcard/Android/data/com.myawesomeapp.app/"; 

File dbdir = new File(DB_PATH); 
dbdir.mkdirs(); 
+3

不,你不應該使用硬編碼的路徑,而不是調用適當的API。這樣做會導致對特定實施細節的不明智依賴。 – 2014-07-24 17:20:01

5
File sdcard = Environment.getExternalStorageDirectory(); 
File f=new File(sdcard+"/dor"); 
f.mkdir(); 

這將創建一個在你的SD卡命名的文件夾多爾。 然後獲取eg-filename.json的文件,該文件手動插入dor文件夾中。像:

File file1 = new File(sdcard,"/dor/fitness.json"); 
....... 
..... 

<使用許可權的android:NAME = 「android.permission.WRITE_EXTERNAL_STORAGE」/>

,不要忘了在清單

3
 //Create File object for Parent Directory 
File wallpaperDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() +File.separator + "wallpaper"); 
if (!wallpaperDir.exists()) { 
wallpaperDir.mkdir(); 
} 


File out = new File(wallpaperDir, wallpaperfile); 
FileOutputStream outputStream = new FileOutputStream(out); 
3

添加代碼,只需填寫Vijay的帖子...


艙單

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

使用

createDirIfNotExists("mydir/"); //Create a directory sdcard/mydir 
createDirIfNotExists("mydir/myfile") //Create a directory and a file in sdcard/mydir/myfile.txt 

你可以檢查錯誤

if(createDirIfNotExists("mydir/")){ 
    //Directory Created Success 
} 
else{ 
    //Error 
} 
6

我面臨同樣的問題。有兩種類型的權限在安卓

  • 危險(訪問聯繫人,編寫到外部存儲......)
  • 普通(普通權限由Android自動批准而危險的權限需要通過Android用戶的批准。)

這裏,就是以在Android 6.0

    0123危險的權限策略
  • 檢查您是否獲得許可
  • 如果您的應用已被授予權限,請繼續並正常執行。
  • 如果您的應用程序沒有權限呢,要求用戶批准
  • 傾聽用戶批准onRequestPermissionsResult

這裏是我的情況:我需要編寫到外部存儲設備。

首先,我檢查我是否有權限:

... 
private static final int REQUEST_WRITE_STORAGE = 112; 
... 
boolean hasPermission = (ContextCompat.checkSelfPermission(activity, 
      Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED); 
if (!hasPermission) { 
    ActivityCompat.requestPermissions(parentActivity, 
       new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
       REQUEST_WRITE_STORAGE); 
} 

然後檢查用戶的認可:

@Override 
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
    super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
    switch (requestCode) 
    { 
     case REQUEST_WRITE_STORAGE: { 
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) 
      { 
       //reload my activity with permission granted or use the features what required the permission 
      } else 
      { 
       Toast.makeText(parentActivity, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show(); 
      } 
     } 
    }  
} 
1
ivmage.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      Intent i = new Intent(
        Intent.ACTION_PICK, 
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 

      startActivityForResult(i, RESULT_LOAD_IMAGE_ADD); 

     } 
    });` 
3

這將使文件夾中與您提供的文件夾名稱SD卡。

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Folder name"); 
     if (!file.exists()) { 
      file.mkdirs(); 
     }