我如何存储具有相同数字但只有重复名称的图像,如“_01.jpg”

时间:2016-06-17 05:05:01

标签: android

我正在存储一个带有数字的图像作为其名称。如何使用相同的数字存储图像,但只能使用“_01.jpg”。

更新:我两次拍摄同一张照片。第一张图片名称是“123.jpg”,当我第二次点击相同的图片并保存时,名称应为“123_01.jpg”。我该怎么办?

String s3 = editText.getText().toString();
{ 
    Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    File f = new File(Environment.getExternalStorageDirectory(), s3 + ".jpg");
    chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); 
    imagaeToUploadUri = Uri.fromFile(f); 
    startActivityForResult(chooserIntent, CAMERA_PHOTO);
}

1 个答案:

答案 0 :(得分:1)

您可以使用exists方法检查给定文件是否已存在,并使用while循环来递增计数器以查找下一个可用文件名。

这是一个让你入门的例子......

String s3 = editText.getText().toString();

File dir = Environment.getExternalStorageDirectory();
String filename = s3 + ".jpg";

File f;
int c = 0;
while ((f = new File(dir, filename)).exists())   // f is assigned within the loop condition
{
    filename = s3 + "_" + c + ".jpg";
    c++;
}

假设s3是“somefile”,这会将f分配给somefile.jpgsomefile_0.jpgsomefile_1.jpg等,直到找到可用的文件名(在直到f不存在的其他词。循环结束后,文件应该可以使用了......

Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); 
imagaeToUploadUri = Uri.fromFile(f); 
startActivityForResult(chooserIntent, CAMERA_PHOTO);