Validate a file name on Windows Validate a file name on Windows windows windows

Validate a file name on Windows


Given the requirements specified in the previously cited MSDN documentation, the following regex should do a pretty good job:

public static boolean isValidName(String text){    Pattern pattern = Pattern.compile(        "# Match a valid Windows filename (unspecified file system).          \n" +        "^                                # Anchor to start of string.        \n" +        "(?!                              # Assert filename is not: CON, PRN, \n" +        "  (?:                            # AUX, NUL, COM1, COM2, COM3, COM4, \n" +        "    CON|PRN|AUX|NUL|             # COM5, COM6, COM7, COM8, COM9,     \n" +        "    COM[1-9]|LPT[1-9]            # LPT1, LPT2, LPT3, LPT4, LPT5,     \n" +        "  )                              # LPT6, LPT7, LPT8, and LPT9...     \n" +        "  (?:\\.[^.]*)?                  # followed by optional extension    \n" +        "  $                              # and end of string                 \n" +        ")                                # End negative lookahead assertion. \n" +        "[^<>:\"/\\\\|?*\\x00-\\x1F]*     # Zero or more valid filename chars.\n" +        "[^<>:\"/\\\\|?*\\x00-\\x1F\\ .]  # Last char is not a space or dot.  \n" +        "$                                # Anchor to end of string.            ",         Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS);    Matcher matcher = pattern.matcher(text);    boolean isMatch = matcher.matches();    return isMatch;}

Note that this regex does not impose any limit on the length of the filename, but a real filename may be limited to 260 or 32767 chars depending on the platform.


Not enough,in Windows and DOS, some words might also be reserved and can not be used as filenames.

CON, PRN, AUX, CLOCK$, NULCOM0, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9LPT0, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9.

See~

http://en.wikipedia.org/wiki/Filename


Edit:

Windows usually limits file names to 260 characters. But the file name must actually be shorter than that, since the complete path (such as C:\Program Files\filename.txt) is included in this character count.

This is why you might occasionally encounter an error when copying a file with a very long file name to a location that has a longer path than its current location.


Well, I think the following method would guarantee a valid file name:

public static boolean isValidName(String text){    try    {        File file = new File(text);        file.createNewFile();        if(file.exists()) file.delete();        return true;    }    catch(Exception ex){}    return false;}

What do you think?