CreateTempFile在Pictures文件夹中返回No Such File或Directory?

时间:2016-03-07 06:10:58

标签: 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).

来自File的文档:

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卡插在设备内。

2 个答案:

答案 0 :(得分:2)

getExternalStoragePublicDirectory()的javadoc明确指出:

  

此目录可能尚不存在,因此您必须确保它存在   在使用之前,例如使用File.mkdirs()。

之后,我认为您还应该检查该目录是否存在。

答案 1 :(得分:0)

File imageFile = null;
    try {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";

        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        boolean pictureDirectoryExists = storageDir.exists();
        if (!pictureDirectoryExists) {
            pictureDirectoryExists = storageDir.mkdirs();
        }
        if (pictureDirectoryExists) {
            imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
            mCurrentPhotoPath = imageFile.getAbsolutePath();            }

    } catch (Exception exc) {
        LOGGER.error("E", exc);
    }
    return imageFile;

我知道这确实是旧帖子,但我遇到了同样的问题。异常的原因是目录不存在。