title: Create files with same name without overwriting java
body: <p>I have seen this question before, But I have not been able to come up with a solution from the suggestions. I need to be able to create a file with the same name without overwriting the old one. Say for example if I have images.txt, If I try to create another file with the same name it should be <code>images(1).txt, images(2).txt</code> and so on. So far I am able to create only first index. Here is My code:</p>
  
  <pre><code>public class Filenames {
  
      public static void main(String[] args) throws IOException {
          String filename = "images.txt";
          File f = new File(getNewFileName(filename));
          f.createNewFile();
  
      }
  
      public static String getFileExtension(String filename) {
          return filename.substring(filename.lastIndexOf("."));
      }
  
      public static String getNewFileName(String filename) throws IOException {
          File aFile = new File(filename);
          int fileNo = 0;
          String newFileName = "";
          if (aFile.exists() &amp;&amp; !aFile.isDirectory()) {
              fileNo++;
              newFileName = filename.replaceAll(getFileExtension(filename), "(" + fileNo + ")" + getFileExtension(filename));
          } else if (!aFile.exists()) {
              aFile.createNewFile();
              newFileName = filename;
          }
          return newFileName;
      }
  }
  </code></pre>
  
  <p>What am I Missing?</p>