我正在尝试将文件保存到以下位置FileOutputStream fos = new FileOutputStream("/sdcard/Wallpaper/"+fileName);但我收到异常java.io.FileNotFoundException但是,当我将路径设置为"/sdcard/"时,它可以工作。

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

有人可以建议如何使用代码创建directory and sub-directory吗?

最佳答案

如果创建包裹顶层目录的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卡以外的东西(例如内置闪存,iPhone或iPhone)可能会更改此目录。无论哪种方式,您都应记住,由于SD卡可能已卸下,因此需要检查以确保它确实在其中。

更新:由于API级别4(1.6),您还必须请求权限。这样的东西(在 list 中)应该起作用:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

10-07 19:12
查看更多