Re: Sanitize file name
Andrew Thompson wrote:
Philipp wrote:
..
Is there a way to test if a filename is valid on a certain platform?
This E.G. makes for some interesting results, though I
am not sure if it really helps with the problem. The
programmer would need to specially account for the
'last situation' where the user puts a character in the
name that is used as (or is generally understood to be)
a path separator.
Irritatingly, although Win's path separator is '\', '/'
will apparently also work (here, on this Win XP pro
box).
<sscce>
import java.io.File;
import java.io.IOException;
class TestFileName {
static void testFileName(String name) {
try {
File f = new File(name);
System.out.println( f.getCanonicalPath() );
} catch(IOException ioe) {
System.err.println( ioe.getMessage() + " '" + name + "'");
}
}
public static void main(String[] args) {
testFileName("123.txt");
testFileName("12?3.txt");
testFileName("12[3.txt");
testFileName("12{3.txt");
testFileName("12!3.txt");
testFileName("12/3.txt");
}
}
</sscce>
[OP]
D:\projects\123.txt
Invalid argument '12?3.txt'
D:\projects\12[3.txt
D:\projects\12{3.txt
D:\projects\12!3.txt
D:\projects\12\3.txt
Press any key to continue . . .
[\OP]
As far as I know the invalid characters for filenames are:
On Windows \ / : * ? " < > |
On UNIX :
Running your SSCCE with these signs (although in a different order)
gives (on WinXP):
[OP]
Invalid argument '12?3.txt'
D:\workspace\test\123.txt
Syntaxe du nom de fichier, de r?pertoire ou de volume incorrecte '12:3.txt'
D:\workspace\test\12[3.txt
D:\workspace\test\12{3.txt
D:\workspace\test\12!3.txt
D:\workspace\test\12\3.txt
D:\workspace\test\12;3.txt
D:\workspace\test\12<3.txt
D:\workspace\test\12>3.txt
Invalid argument '12*3.txt'
D:\workspace\test\12"3.txt
Syntaxe du nom de fichier, de r?pertoire ou de volume incorrecte '12|3.txt'
[/OP]
Note that the getCanonicalPath() method throws IOException for only some
of them. So this does not seem a good method to identify bad chars.
The method described in
http://forum.java.sun.com/thread.jspa?threadID=629458&start=0&tstart=0
(thanks Sabine for the link) actually creates the file. Well, that
definitely works, but it's really ugly (IMHO).
Best regards
Phil