问题描述
我想我的文件保存到以下位置 - 的FileOutputStream FOS =新的FileOutputStream(/ SD卡/壁纸/+文件名);
但我发现兴田异常 java.io.FileNotFoundException
但是,当我把路径/ SD卡/
它的工作原理。
I'm trying to save my file to the following locationFileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName);
but I'm getting hte 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.
有人建议如何创建一个通过code目录和子目录
?
Can someone suggest how to create a directory and sub-directory
via code?
推荐答案
如果您创建一个文件一>对象包装了顶级目录,你可以调用它的 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'la的iPhone)。无论哪种方式,你应该记住,你需要检查,以确保它实际上是有作为的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" />
这篇关于如何在SD卡中自动生成目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!