Creating valid file names in Java

I create file names based on dynamic values ​​such as company name and first / last name.

I would like to confirm that the file name is valid before trying to create the file. This means that it does not contain any illegal characters and replaces them if they do.

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

+5
source share
2 answers

In Java 7, the new method java.nio.file.Paths.get(String path)will call InvalidPathExceptionif the path contains invalid characters for a specific file system, but in Java 6 or earlier, unfortunately, there is no such function.

Since the valid characters and length of the file name depend on the platform (or even the file system), you may not have a better option than trying to create a file and see if it works. In Java 6, creating a FileOutputStream with an illegal path will raise a rather nonspecific FileNotFoundException.

+5
source

Well, you must strip it, even if it is a legitimate file name, because it can contain a path, in which case the user can provide .. /../../../../../../. ./etc/passwd etc.

+3
source

All Articles