android - CreateTempFile 在图片文件夹中返回没有这样的文件或目录?

标签 android android-file

这是我的代码:

String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
      imageFileName,  /* prefix */
      ".jpg",         /* suffix */
      storageDir      /* directory */
);

但是,我的应用程序间歇性地在 File.createTempFile 处抛出错误:

java.io.IOException: open failed: ENOENT (No such file or directory).

来自文件的文档:

Parameters:
prefix the prefix to the temp file name.
suffix the suffix to the temp file name.
directory the location to which the temp file is to be written, or null for the default location for temporary files, which is taken from the "java.io.tmpdir" system property. It may be necessary to set this property to an existing, writable directory for this method to work properly.

Returns:
the temporary file.

Throws:
IllegalArgumentException - if the length of prefix is less than 3.
IOException - if an error occurs when writing the file.

写入临时文件失败的可能性有哪些?因为我指向外部存储并且我的外部 SD 卡插入设备内部。

最佳答案

getExternalStoragePublicDirectory() 的 javadoc特别指出:

this directory may not yet exist, so you must make sure it exists before using it such as with File.mkdirs().

在那之后,我认为你还应该检查一下目录是否存在。

关于android - CreateTempFile 在图片文件夹中返回没有这样的文件或目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35837265/

相关文章:

java - Android 日期选择器,无法选择回溯日期,只能选择今天和 future 日期

java - Android - FirebaseListAdapter 复制运行时布局更改

java - Android 空指针异常 ListFragment

android - Espresso 失败时设置构建失败

android - 如何访问/存储/模拟/0/

android - 我如何从内存中查询歌曲的uri

android - 如何使用文件提供程序将视频从一个应用程序共享到另一个应用程序?

android - 在 Android 的 TextEdit/TextView 中输入乌尔都语/阿拉伯语

Android 保存文件权限被拒绝

java - 应用“按名称排序”时顺序错误