tags:

views:

311

answers:

2

I am creating filenames based on dynamic values such as company name and forename/surname.

I would then like to verify that the filename is valid before attempting to create the file. That is check it doesn't contain any illegal characters, and replace them if they do.

I could of course just use a regular expression, but was wondering if there was an existing method in something like commons-lang or commons-io that does this?

+3  A: 

Well, you should strip it even if it is a legal filename, because it might contain a path, in which case a user might supply ../../../../../../../../etc/passwd etc.

abyx
+4  A: 

With Java 7, the new method java.nio.file.Paths.get(String path) will throw an InvalidPathException if the path contains illegal characters for the specific file system, but in Java 6 or earlier, there is unfortunately no such function.

Since the allowed characters in and length of a file name are highly platform (or even file system) dependent, you might have no better option than to try to create the file and see if it fails. In Java 6, creating a FileOutputStream with an illegal path will throw a rather unspecific FileNotFoundException.

jarnbjo