Validate a file name on Windows

后端 未结 11 1980
一生所求
一生所求 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: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.

提交回复
热议问题