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.
Try this link partly answers your query.
https://stackoverflow.com/a/805504/1961652
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"**/myfile*.txt"});
scanner.setBasedir("C:/Temp");
scanner.setCaseSensitive(false);
scanner.scan();
String[] files = scanner.getIncludedFiles();
once you have got the correct set of files, append a proper suffix to create a new file.
Untested Code:
File f = new File(filename);
String extension = "";
int g = 0;
int i = f.lastIndexOf('.');
extension = fileName.substring(i+1);
while(f.exists()) {
if (i > 0)
{ f.renameTo(f.getPath() + "\" + (f.getName() + g) + "." + extension); }
else
{ f.renameTo(f.getPath() + "\" + (f.getName() + g)); }
g++;
}
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
You might also benefit from using the apache commons-io library. It has some usefull file manipulation methods in class FileUtils and FilenameUtils.