public static File getUniqueFile ( File srcFile , char extSeparator ) throws IOException { if ( srcFile == null ) { throw new IllegalArgumentException ( "srcFile must not be null" ) ; } String path = getFullPath ( srcFile . getCanonicalPath ( ) ) ; String name = removeExtension ( srcFile . getName ( ) ) ; String ext = getExtension ( srcFile . getName ( ) ) ; String newName ; if ( ext != null && ! ext . isEmpty ( ) ) { newName = name + extSeparator + ext ; } else { newName = name ; } int count = 0 ; File destFile = new File ( path , newName ) ; while ( destFile . exists ( ) ) { count ++ ; if ( ext != null && ! ext . isEmpty ( ) ) { newName = name + "-" + count + extSeparator + ext ; } else { newName = name + "-" + count ; } destFile = new File ( path , newName ) ; } return ( count == 0 ? srcFile : destFile ) ; }
Returns a file name that does not overlap in the specified directory . If a duplicate file name exists it is returned by appending a number after the file name .