Reputation: 5985
I'm writing a camera2 app in android and when I try to save the image, something adds extra numbers on the end of the filename before the '.jpg'
I have a feeling it's because of the createTempFile()
method, but here's my code:
File createImageFile() throws IOException {
++image_id;
String timestamp = new SimpleDateFormat("yyyyMMdd").format(new Date());
String subFolder = "";
if(pref_session_unique_gallery.equals("yes")){
if(event_name != null){
subFolder = event_name;
} else {
subFolder = timestamp;
}
} else {
subFolder = "_GEN";
}
if(event_name == null){
imageFileName = "CPB_"+timestamp+"-"+image_id;
} else {
imageFileName = "CPB_"+event_name+"_"+timestamp+"-"+image_id;
}
imageStorageDirectory = Environment.getExternalStorageDirectory() + File.separator + "CPB" + File.separator + subFolder;
imageFinalFileName = imageFileName;
Toast.makeText(getApplicationContext(), imageStorageDirectory + "/" + imageFileName, Toast.LENGTH_LONG).show();
File storageDirectory = new File(imageStorageDirectory);
storageDirectory.mkdir();
File image = File.createTempFile(imageFileName, ".jpg", storageDirectory);
return image;
}
When I read the toast it gives me the correct path and filename that I am expecting, but when I look in my folder view, the picture has a lot of extra numbers on it.
For example, the picture name should be CPB_20160120-1.jpg
but it currently reads CPB_20160120-1484291604.jpg
If it makes a difference, the file was saved at 6:37 PM
two more examples:
should be: CPB_20160120-2.jpg
is: CPB_20160120-22140921986.jpg
should be: CPB_20160120-3.jpg
is: CPB_20160120-3-965716644.jpg
Not sure where those extra numbers are coming from when the file saves...
Upvotes: 4
Views: 3238
Reputation: 33914
Those random numbers are explicitly generated by createTempFile()
, as seen in the source code.
You probably don't want to use temporary files anyway, thus I'd recommend to create normal files:
File image = new File(storageDirectory, imageFileName + ".jpg");
Upvotes: 8
Reputation: 5020
According implementation of used method new file is created with extra random integer new File(tmpDirFile, prefix + Math.randomIntInternal() + suffix)
public static File createTempFile(String prefix, String suffix, File directory)
throws IOException {
// Force a prefix null check first
if (prefix.length() < 3) {
throw new IllegalArgumentException("prefix must be at least 3 characters");
}
if (suffix == null) {
suffix = ".tmp";
}
File tmpDirFile = directory;
if (tmpDirFile == null) {
String tmpDir = System.getProperty("java.io.tmpdir", ".");
tmpDirFile = new File(tmpDir);
}
File result;
do {
result = new File(tmpDirFile, prefix + Math.randomIntInternal() + suffix);
} while (!result.createNewFile());
return result;
}
Upvotes: 2