Validate a file name on Windows

后端 未结 11 1869
一生所求
一生所求 2020-11-29 23:28
public static boolean isValidName(String text)
{
    Pattern pattern = Pattern.compile(\"^[^/./\\\\:*?\\\"<>|]+$\");
    Matcher matcher = pattern.matcher(text         


        
相关标签:
11条回答
  • 2020-11-30 00:06

    Here you can find which file names are allowed.

    The following characters are not allowed:

    • < (less than)
    • (greater than)

    • : (colon)
    • " (double quote)
    • / (forward slash)
    • \ (backslash)
    • | (vertical bar or pipe)
    • ? (question mark)
    • * (asterisk)

    • Integer value zero, sometimes referred to as the ASCII NUL character.

    • Characters whose integer representations are in the range from 1 through 31, except for alternate data streams where these characters are allowed. For more information about file streams, see File Streams.
    • Any other character that the target file system does not allow.
    0 讨论(0)
  • 2020-11-30 00:06

    Not sure how to implement it in Java (either Regex or own method). But, Windows OS has the following rules to create file/directory in the file system:

    1. Name is not only be Dots
    2. Windows device names like AUX, CON, NUL, PRN, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9, cannot be used for a file name nor for the first segment of a file name (i.e. test1 in test1.txt).
    3. Device names are case insensitive. (i.e. prn, PRN, Prn, etc. are identical.)
    4. All characters greater than ASCII 31 to be used except "*/:<>?\|

    So, the program needs to stick with these rules. Hope, it covers the validation rules for your question.

    0 讨论(0)
  • 2020-11-30 00:11

    This solution will only check if a given filename is valid according to the OS rules without creating a file.

    You still need to handle other failures when actually creating the file (e.g. insufficient permissions, lack of drive space, security restrictions).

    import java.io.File;
    import java.io.IOException;
    
    public class FileUtils {
      public static boolean isFilenameValid(String file) {
        File f = new File(file);
        try {
           f.getCanonicalPath();
           return true;
        }
        catch (IOException e) {
           return false;
        }
      }
    
      public static void main(String args[]) throws Exception {
        // true
        System.out.println(FileUtils.isFilenameValid("well.txt"));
        System.out.println(FileUtils.isFilenameValid("well well.txt"));
        System.out.println(FileUtils.isFilenameValid(""));
    
        //false
        System.out.println(FileUtils.isFilenameValid("test.T*T"));
        System.out.println(FileUtils.isFilenameValid("test|.TXT"));
        System.out.println(FileUtils.isFilenameValid("te?st.TXT"));
        System.out.println(FileUtils.isFilenameValid("con.TXT")); // windows
        System.out.println(FileUtils.isFilenameValid("prn.TXT")); // windows
        }
      }
    
    0 讨论(0)
  • 2020-11-30 00:17

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

    CON, PRN, AUX, CLOCK$, NUL
    COM0, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9
    LPT0, 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.

    0 讨论(0)
  • 2020-11-30 00:17

    You can check all the reserved names (AUX, CON, and the like) and then use this code:

    bool invalidName = GetFileAttributes(name) == INVALID_FILE_ATTRIBUTES && 
            GetLastError() == ERROR_INVALID_NAME;
    

    to check for any additional restriction. But note that if you check for a name in a non existant directory you will get ERROR_PATH_NOT_FOUND whether the name is really valid or not.

    Anyway, you should remember the old saying:

    It's easier to ask for forgiveness than it is to get permission.

    0 讨论(0)
  • 2020-11-30 00:18

    Posting a new answer because I dont have the rep threshold to comment on Eng.Fouad's code

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

    A small change to your answer that prevents deleting a pre-existing file. Files only get deleted if they were created during this method call, while the return value is the same.

    0 讨论(0)
提交回复
热议问题