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.txt
exists in destination folder - I need to copy my file with name myfile_1.txt
And same time if I have a file myfile.txt
, but destintation folder contains myfile.txt
and myfile_1.txt
- generated filename has to be myfile_2.txt
So the functionality is very similar to the creation of folders in Microsoft operating systems.
What's the best approach to do that?
Using commons-io:
This will check if for instance
file.txt
exist and will returnfile-1.txt
Try this link partly answers your query.
https://stackoverflow.com/a/805504/1961652
once you have got the correct set of files, append a proper suffix to create a new file.
You might also benefit from using the apache commons-io library. It has some usefull file manipulation methods in class FileUtils and FilenameUtils.
Untested Code: