简体   繁体   中英

How to validate file path?

Edit 1

I am stuck on a little problem and the guy who I normally turn to is, believe it or not, in Australia on his honeymoon, how inconsiderate is that.

The problem is that I have worked on trying to get a boolean which will either let me know if the file path is correct or not.

The problem is that it always returns false,

I have tried the following sample data

    c:\Lingerie\
    c:\\Lingerie\\
    c:\\
    c:\

Edit

This is the input screen that I have developed so far. I have already thought of having extra white spaces, so I already popped in the trim command.

在此处输入图片说明 They all have returned false. Here is the method that I'm using and the code that calls it.

    dbFilePath = (text.getText()).trim();
    bool03 = busLog.isFilePath(dbFilePath);
    System.out.println("The result is " + bool03);

And the method is called is

public boolean isFilePath(String filePath) {

    return discreetLog.isFilePathMatched(filePath);
}

And which calls

public boolean isFilePathMatched(String myFilePath){

    String regularExpression = "([a-zA-Z]:)?(\\\\[a-zA-Z0-9_.-]+)+\\\\?";

    Pattern pattern = Pattern.compile(regularExpression);

    return Pattern.matches(regularExpression, myFilePath);
}

I don't know if it is my code or an input error.

The first path of your sample is actually matching the regex correctly.

To match the second and fourth, you have to allow double backslashes. Just add \\\\\\\\? on the right of the previous backslashes in your regex.

To match the third and fourth, you need to make the second group optional. Currently it is used with the operator + . Use * instead.

Therefore if you replace your regex with this one:

String regularExpression = "([a-zA-Z]:)?(\\\\\\\\?[a-zA-Z0-9_.-]+)*\\\\?\\\\?";

it will match all your paths, and nothing more.

If you still can not match your sample data, then there is a problem somewhere else in your code. You can try posting an SSCCE .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM