问题
In my application I use a button to launch Camera application and save picture to specific folder on sdCard naming it by current date and time. When I hardcode the name for the picture, it works fine, but if I'm trying to put date in the name it doesn't work at all.
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), Constants.IMAGE_FOLDER_URI);
imagesFolder.mkdirs();
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh:mm:ss", d.getTime());
File image = new File(imagesFolder, s.toString() + ".jpg"); //this line doesn't work
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivity(imageIntent);
If I put:
s = "some_name";
then it works, but I need current date and time in image name.
回答1:
Colon :
is not a valid character in a file name, that is why it is failing to create such a file.
Try change your name pattern to something like this:
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
回答2:
Put this code and try:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
回答3:
Here is an alternate solution:
File cameraFolder;
if (android.os.Environment.getExternalStorageState().equals
(android.os.Environment.MEDIA_MOUNTED))
cameraFolder = new File(android.os.Environment.getExternalStorageDirectory(),
"YOUR_FOLDER_NAME/");
else
cameraFolder= StatusUpdate.this.getCacheDir();
if(!cameraFolder.exists())
cameraFolder.mkdirs();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
String timeStamp = dateFormat.format(new Date());
String imageFileName = "picture_" + timeStamp + ".jpg";
File photo = new File(Environment.getExternalStorageDirectory(),
"YOUR_FOLDER_NAME/" + imageFileName);
If you want just the TimeStamp as the image name, you can remove "picture_" +
from the String imageFileName
.
回答4:
use this
File image = new File(imagesFolder, s+ "Rj.jpg");
来源:https://stackoverflow.com/questions/15728269/saving-image-to-sd-with-current-date-and-time-in-name-doesnt-work