Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating valid filenames in Java

Tags:

java

regex

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?

like image 738
pledge Avatar asked Oct 02 '09 12:10

pledge


People also ask

How do I create a valid file name?

Supported characters for a file name are letters, numbers, spaces, and ( ) _ - , . *Please note file names should be limited to 100 characters. Characters that are NOT supported include, but are not limited to: @ $ % & \ / : * ?

How do you create a new file and write in Java?

Example 1: Java Program to Create a File java is equivalent to // currentdirectory/JavaFile. java File file = new File("JavaFile. java"); We then use the createNewFile() method of the File class to create new file to the specified path.


2 Answers

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.

like image 68
jarnbjo Avatar answered Sep 30 '22 12:09

jarnbjo


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.

like image 31
abyx Avatar answered Sep 30 '22 12:09

abyx