如何在SD卡上自动创build目录

我试图将我的文件保存到以下位置
FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName); 但我得到了exceptionjava.io.FileNotFoundException
但是,当我把path作为"/sdcard/"它的工作。

现在我假设我无法以这种方式自动创build目录。

有人可以build议如何使用代码创build一个directory and sub-directory

如果创build一个包装顶层目录的File对象,则可以调用它的mkdirs()方法来构build所有需要的目录。 就像是:

 // 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 Card”目录可能是明智之举,因为如果手机出现了SD卡以外的内容,这可能会改变(例如内置闪存,a'la苹果手机)。 无论哪种方式,你应该记住,你需要检查,以确保它实际上在SD卡可能会被删除。

更新:由于API级别4(1.6),你也必须要求权限。 像这样的东西(在清单中)应该工作:

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

有同样的问题,只是想补充一点,AndroidManifest.xml也需要这个权限:

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

这是对我有用的东西。

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

其实我用了@fiXedd的一部分,它对我很有帮助:

  //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()来创build完整的path

使用API​​ 8及更高版本时,SD卡的位置已更改。 @ fiXedd的答案是好的,但为了更安全的代码,你应该使用Environment.getExternalStorageState()来检查媒体是否可用。 然后,您可以使用getExternalFilesDir()导航到您想要的目录(假设您使用API​​ 8或更高版本)。

您可以在SDK文档中阅读更多内容 。

确保存在外部存储: 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); } 

我面临同样的问题。 Android中有两种types的权限:

  • 危险 (访问联系人,写入外部存储…)
  • 正常 (普通权限由Android自动批准,而危险权限需要由Android用户批准。)

这是在Android 6.0中获取危险权限的策略

  • 检查你是否有权限
  • 如果您的应用程序已被授予权限,请继续并正常执行。
  • 如果您的应用还没有权限,请要求用户批准
  • 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(); } } } } 

我面临同样的问题,无法在Galaxy S上创build目录,但能够在Nexus和Samsung Droid上成功创build目录。 我如何解决它是通过添加以下代码行:

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

不要忘记确保文件/文件夹名称中没有特殊字符。 当我使用variables设置文件夹名称时,发生了“:”

文件/文件夹名称中不允许使用字符

“* /:<>?\ |

你可能会发现这个代码在这种情况下有帮助。

下面的代码将删除所有“:”,并用“ – ”replace它们

 //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"); } } 
 File sdcard = Environment.getExternalStorageDirectory(); File f=new File(sdcard+"/dor"); f.mkdir(); 

这将在您的SD卡上创build一个名为dor的文件夹。 然后获取手动插入到dor文件夹中的eg-filename.json文件。 喜欢:

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

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

并且不要忘记在清单中添加代码

  //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); 

刚刚完成Vijay的职位


performance

 uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 

function

 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 } 

这将使您提供的文件夹名称与SD卡中的文件夹。

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

您可以使用/ sdcard /而不是Environment.getExternalStorageDirectory()

 private static String DB_PATH = "/sdcard/Android/data/com.myawesomeapp.app/"; File dbdir = new File(DB_PATH); dbdir.mkdirs(); 
 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); } });`