Android 使用名称中的当前日期和时间将图像保存到sd不会';行不通

Android 使用名称中的当前日期和时间将图像保存到sd不会';行不通,android,image,datetime,save,android-camera,Android,Image,Datetime,Save,Android Camera,在我的应用程序中,我使用一个按钮启动相机应用程序,并将图片保存到SD卡上的特定文件夹中,按当前日期和时间命名。当我硬编码图片的名字时,效果很好,但是如果我试图在名字中加上日期,它根本不起作用 Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); File imagesFolder = new File(Environment.getExternalStorageDirectory(

在我的应用程序中,我使用一个按钮启动相机应用程序,并将图片保存到SD卡上的特定文件夹中,按当前日期和时间命名。当我硬编码图片的名字时,效果很好,但是如果我试图在名字中加上日期,它根本不起作用

 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);
如果我说:

s = "some_name";

然后它工作,但我需要图像名称中的当前日期和时间。

冒号
不是文件名中的有效字符,这就是它无法创建这样一个文件的原因。 尝试将您的姓名模式更改为以下内容:

CharSequence s  = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());

以下是另一种解决方案:

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);
如果只需要时间戳作为图像名称,可以从
字符串imageFileName
中删除
“picture”+
,然后尝试:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
用这个

File image = new File(imagesFolder, s+ "Rj.jpg"); 

它不起作用,因为正如前面提到的:冒号在文件名中不是有效字符。android API版本22有解决方案吗?这是最低限度的工作27@Dev_Man:这不太可能在至少27个版本上工作。这个解决方案很久以前就发布了,效果很好。也就是说,我不再使用此代码,而是开始使用库来处理图像拾取/捕获任务。省去了确保多制造商设备兼容性的麻烦。