tags:

views:

105

answers:

2

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 picture*1* 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 same 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...

+1  A: 

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
        }
    }
}
Michael Petrotta
You WILL want a binary search on that, if you allow the user to have arbitrary number of save files.
Thorbjørn Ravn Andersen
@Thorbjørn: probably true, but depends on the desired behavior if a file somewhere in the middle has been deleted.
Michael Petrotta
+1  A: 

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.

rsp
+1 for suggesting a Format. A more recent createTempFile() link might be in order. :-)
trashgod
thanks rsp :-) ..
Jessy