Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CreateTempFile returns No Such File or Directory in Pictures folder?

So here is my code:

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 */
);

However, my application intermittently throws error at File.createTempFile:

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

From the documentation of 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.

What are the possibilities of failing writing the temporary file? Since I point to external storage and my external sd card is plugged inside device.

like image 924
Rendy Avatar asked Mar 07 '16 06:03

Rendy


2 Answers

The javadoc for getExternalStoragePublicDirectory() specifically states that:

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

After that, I think you should also still check to see if the directory exists.

like image 107
Doug Stevenson Avatar answered Oct 01 '22 09:10

Doug Stevenson


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;

I know it is really old post but I had same problem. The reason of Exception is directory is not exists.

like image 35
Patryk Avatar answered Oct 01 '22 11:10

Patryk