I want to add an index to a filename if the file already exists, so that I don\'t overwrite it.
Like if I have a file myfile.txt
and same time myfile.
Using commons-io:
private static File getUniqueFilename( File file )
{
String baseName = FilenameUtils.getBaseName( file.getName() );
String extension = FilenameUtils.getExtension( file.getName() );
int counter = 1
while(file.exists())
{
file = new File( file.getParent(), baseName + "-" + (counter++) + "." + extension );
}
return file
}
This will check if for instance file.txt
exist and will return file-1.txt