我正在尝试将一个图像文件写入到指定目录下的公有图库文件夹中,但我一直收到一个错误,提示我无法打开该文件,因为它是一个目录。
到目前为止,我所掌握的内容如下
//set the file path
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + directory;
File outputFile = new File(path,"testing.png");
outputFile.mkdirs();
FileOutputStream out = new FileOutputStream(outputFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
其中,目录是应用程序名称。因此,应用程序保存的所有照片都将放入该文件夹/目录中,但我一直收到错误消息
/storage/sdcard0/Pictures/appname/testing.png: open failed: EISDIR (Is a directory)
即使我不尝试将它放在一个目录中,并将变量path转换为一个文件,例如
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
我不明白这个错误,但是照片仍然没有出现在图库中。
*回答问题是,当我最初运行这段代码时,它创建了一个名为testing.png的目录,因为我在目录中创建文件之前创建目录失败。因此,解决方案是首先创建目录,然后使用单独的文件写入该目录,如下所示
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + File.separator + directory;
//directory is a static string variable defined in the class
//make a file with the directory
File outputDir = new File(path);
//create dir if not there
if (!outputDir.exists()) {
outputDir.mkdir();
}
//make another file with the full path AND the image this time, resized is a static string
File outputFile = new File(path+File.separator+resized);
FileOutputStream out = new FileOutputStream(outputFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
注意:如果您犯了与我开始时相同的错误,则可能需要进入存储并手动删除目录
https://stackoverflow.com/questions/12967046
复制相似问题