How to save a file with an incrementing suffix - file1, file2, etc
Scenario: I save my drawing with a file name as picture. After a while I made some changes on the file picture and save it again.
Since both file have the same name, is it possible that the new file automatically saved as picture1 without need to manually change the file name in the program? ... I means automatically add number at the end of the file name if the file have the s开发者_开发百科ame name?
so at the end if I made changes on the files so many times, I will have many files named as picture, picture1, picture2, picture3...
You could use the create temp file method for this, use:
- as prefix the basename of your file, in this case it would be "picture"
- as suffix the image type, for instance ".png"
The file created will be unique by definition.
Another way is to create a unique filename based on the current time, as in:
SimpleDateFormat fmt = new SimpleDateFormat("picture_yyyyMMdd_HHmmss.png");
String filename = fmt.format(new Date());
This would give you meaningfull filenames with regards to edit history.
Sure, if you program it so. If your desired filename exists check to see if a file with the same name, with an increasing integer starting at 1, exists. Once you find one that doesn't exist, use it as the name. Make sure to do the right thing with file extensions (you probably want file2.txt, not file.txt.2).
if filename exists
{
loop suffix from 1 to some limit
{
if filename + suffix doesn't exist
{
exit loop and use this name
}
}
}
精彩评论