Re: Making file name unique
laredotornado wrote:
[...]
Thanks. My original intention was to simplify the code I already
had ...
private File uniquifyLocalFile(final File p_localFile) {
File localFile = p_localFile;
if(localFile != null) {
Integer revision = 0;
final String fileName = localFile.getName();
final Integer index = fileName.indexOf('.');
while(localFile.exists()) {
localFile = new File(localFile.getParent(),
fileName.substring(0, index) + "-" +
revision++ +
fileName.substring(index));
} // while
} // if
return localFile;
}
Just a couple of comments ...
First, you might want fileName.lastIndexOf('.'), depending
on whether you think "the extension" of foo.11Nov.txt is .txt
or .11Nov.txt.
Second, you need to handle the case where the file name
contains no dot at all. Presumably, given a filename foo you
would rather look at foo-1, foo-2, ... than get an exception
thrown at your head.
Third, you need to decide what to do if the given filename
already looks like foo-42: Do you want to try foo-42-1, or move
on to foo-43?
Fourth -- and this one's the big, gaping hole -- you need to
realize that the state of the file system may change between the
moment you call localFile.exists() and the moment you create the
file and start writing to it. If two people both send you foo.txt
at about the same time, both of them might find that there's no
foo.txt already there, and both may then start writing to it ...
Personally, I'd skip the exists() calls and use createNewFile()
instead: it does the existence test and the file creation in one
indivisible step.
but it looks like even if I use the reg exp strategy suggested here, I
will still have to do a loop to find what hte next non-existent file
is. In fact, I'm thinking the code would be lengthier than what I
already have. If you think differently, please let me know.
Yes, you need more code. Different code, at any rate.
--
Eric Sosman
esosman@ieee-dot-org.invalid