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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With