Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

java - Validate a file name on Windows

public static boolean isValidName(String text)
{
    Pattern pattern = Pattern.compile("^[^/./\:*?"<>|]+$");
    Matcher matcher = pattern.matcher(text);
    boolean isMatch = matcher.matches();
    return isMatch;
}

Does this method guarantee a valid filename on Windows?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).          
" +
        "^                                # Anchor to start of string.        
" +
        "(?!                              # Assert filename is not: CON, PRN, 
" +
        "  (?:                            # AUX, NUL, COM1, COM2, COM3, COM4, 
" +
        "    CON|PRN|AUX|NUL|             # COM5, COM6, COM7, COM8, COM9,     
" +
        "    COM[1-9]|LPT[1-9]            # LPT1, LPT2, LPT3, LPT4, LPT5,     
" +
        "  )                              # LPT6, LPT7, LPT8, and LPT9...     
" +
        "  (?:\.[^.]*)?                  # followed by optional extension    
" +
        "  $                              # and end of string                 
" +
        ")                                # End negative lookahead assertion. 
" +
        "[^<>:"/\\|?*\x00-\x1F]*     # Zero or more valid filename chars.
" +
        "[^<>:"/\\|?*\x00-\x1F\ .]  # Last char is not a space or dot.  
" +
        "$                                # 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...