Note that there are some explanatory texts on larger screens.

plurals
  1. POReplace and increment the number in the filename in an Android app
    text
    copied!<p>Please see below (both) answers for solution.</p> <hr> <p>I can't seem to get my logic right, and for some reason this has really got me, yet it seems (and probably is) so simple. What I'd like to do is to capture an image, and, if it exists, increment the number. I.e. photo1.jpg exists, so save new file as photo2.jpg, etc.</p> <p>At the moment when I run my code, and I take a picture, "photo.jpg" is saved, then with the next capture, "photo1.jpg" is saved, then "photo11.jpg", and then "photo111.jpg", etc.</p> <p>Here is my code:</p> <pre><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(); } } } </code></pre> <p>Any help is much appreciated.</p> <p>Thanks.</p> <hr> <p>I've implemented the below solution, and now I only end up with 2 files no matter how many images I capture. 'photo.jpg' and 'photo1.jpg' were successfully saved, but no other image was saved. They're not even being written over. Any help?</p> <p>Code now follows:</p> <pre><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++; 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(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload