如何在SD卡上自动创建目录
我正在尝试将我的文件保存到以下位置FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName);
但我收到异常 java.io.FileNotFoundException
但是,当我将路径设置为 "/sdcard/"
时,它可以工作.
I'm trying to save my file to the following locationFileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName);
but I'm getting the exception java.io.FileNotFoundException
However, when I put the path as "/sdcard/"
it works.
现在我假设我无法通过这种方式自动创建目录.
Now I'm assuming that I'm not able to create directory automatically this way.
有人可以建议如何使用代码创建目录和子目录
?
Can someone suggest how to create a directory and sub-directory
using code?
如果你创建了一个 File 包装顶级目录的对象,您可以将其称为 mkdirs() 方法来构建所有需要的目录.类似的东西:
If you create a File object that wraps the top-level directory you can call it's mkdirs() method to build all the needed directories. Something like:
// 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 卡以外的其他东西(例如内置闪存,a'laiPhone).无论哪种方式,您都应该记住,您需要检查以确保它确实在那里,因为 SD 卡可能会被移除.
Note: It might be wise to use Environment.getExternalStorageDirectory() for getting the "SD Card" directory as this might change if a phone comes along which has something other than an SD Card (such as built-in flash, a'la the iPhone). Either way you should keep in mind that you need to check to make sure it's actually there as the SD Card may be removed.
更新:从 API 级别 4 (1.6) 开始,您还必须请求权限.像这样(在清单中)应该可以工作:
UPDATE: Since API Level 4 (1.6) you'll also have to request the permission. Something like this (in the manifest) should work:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />