title: Android/Java - When a file exists, rename the file
body: <p>I can't seem to get my logic right, I'm trying to rename a file to "photo2.jpg" if, say "photo.jpg" and "photo1.jpg" exists, and so on.</p>
  
  <p>At the moment when I run my code, and I take a picture, only "photo.jpg" and "photo1.jpg" ever exist, and then they get written over if a third and fourth, etc. photo is taken.</p>
  
  <pre><code>String photoName = "photo.jpg";
          String i = "0";
          int num = 0;
  
          File photo = new File(Environment.getExternalStorageDirectory(), photoName);
  
          //for (File file : photo.listFiles()){
          while(photo.exists()) {             
              //if(file.getName().equals("photo.jpg")){
                  //photo.delete();
                  num = Integer.parseInt(i);
                  ++num;
                  String concatenatedNum = Integer.toString(num);
  
                  StringBuffer insertNum = new StringBuffer(photoName);
                  insertNum.insert(5, concatenatedNum);
  
                  photoName = insertNum.toString();
  
                  photo.renameTo(new File(Environment.getExternalStorageDirectory(), photoName));
              //}
          }
  
  
          try {
              FileOutputStream fos=new FileOutputStream(photo.getPath());
  
              //MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle, yourDescription);
  
              //write jpeg to local drive
              fos.write(jpeg[0]);
              fos.close();
          }
          catch (java.io.IOException e) {}
  </code></pre>
  
  <p>Thanks for your time and help!</p>
  
  <hr>
  
  <p><strong>EDIT:</strong> Half solved: I realized I was overwriting the file instead of creating a NEW file. Now I can take multiple pictures and they are saved as their own file. However, the naming of the files is now:</p>
  
  <ul>
  <li>photo.jpg</li>
  <li>photo1.jpg</li>
  <li>photo11.jpg</li>
  <li>photo111.jpg, etc.</li>
  </ul>