Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Stefan Wendelmann
Added: May 24, 2018 1:00 PM
Views: 17
Tags: no tags
  1.   /**
  2.    * This will check if for instance file.txt exist and will return file-1.txt.
  3.    *
  4.    * @param file
  5.    * @return
  6.    */
  7.   public static File getUniqueFilename(File file)
  8.   {
  9.     String baseName = FilenameUtils.getBaseName(file.getName());
  10.     String extension = FilenameUtils.getExtension(file.getName());
  11.     int counter = 1;
  12.     while (file.exists())
  13.     {
  14.       file = new File(file.getParent(), baseName + "-" + (counter++) + "." + extension);
  15.     }
  16.     return file;
  17.   }