Replace and increase the number in the file name in the Android application

See below (both) answers for a solution.


I cannot understand my logic correctly, and for some reason it really led me, but it seems (and probably so) so simple. What I would like to do is capture the image, and if it exists, increase the number. That is, photo1.jpg exists, so save the new file as photo2.jpg, etc.

At that moment when I run my code and I take a picture, “photo .jpg” is saved, then the next time it captures, “photo1.jpg”, then “photo11.jpg” and then “photo .jpg”, photo111. jpg "etc.

Here is my code:

String photoName = "photo.jpg"; String i = "0"; int num = 0; File photo = new File(Environment.getExternalStorageDirectory(), photoName); while(photo.exists()) { //photo.delete(); num = Integer.parseInt(i); num++; String concatenatedNum = Integer.toString(num); StringBuffer insertNum = new StringBuffer(photoName); photoName = insertNum.replace(5, 5, concatenatedNum).toString(); //insert photo = new File(Environment.getExternalStorageDirectory(), photoName); } FileOutputStream fostream = null; try { fostream = new FileOutputStream(photo.getPath()); //MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle, yourDescription); //write jpeg to local drive fostream.write(jpeg[0]); fostream.close(); } catch (IOException e) { e.printStackTrace(); } finally { if(fostream != null) { try { fostream.flush(); fostream.close(); } catch(IOException e) { e.printStackTrace(); } } } 

Any help is greatly appreciated.

Thanks.


I implemented the following solution, and now I only have 2 files, no matter how many images I captured. "photo.jpg" and "photo1.jpg" were successfully saved, but no other image was saved. They are not even written. Any help?

Now the code follows:

  String photoName = "photo.jpg"; String i = "0"; int num = 0; File photo = new File(Environment.getExternalStorageDirectory(), photoName); while(photo.exists()) { //photo.delete(); num = Integer.parseInt(i); num++; photoName = "photo" + num + ".jpg"; photo = new File(Environment.getExternalStorageDirectory(), photoName); //String concatenatedNum = Integer.toString(num); //StringBuffer insertNum = new StringBuffer(photoName); //photoName = insertNum.insert(5, concatenatedNum).toString(); } 
+4
source share
2 answers

Replace the while as follows:

  while(photo.exists()) { num++; photoName = "photo"+num+".jpg"; photo = new File(Environment.getExternalStorageDirectory(), photoName); } 
+7
source

For a new solution - Why do you have the following line?

 num = Integer.parseInt(i); 

i never changes, so num also never changes. It seems that the code will be just infinitely closed. It should work if you delete this line.

+2
source

Source: https://habr.com/ru/post/1482866/


All Articles