简体   繁体   中英

Validate String input COULD be a valid path

I wish to validate a string path. I don't want to check that the path exists or create the path (that includes create + then delete), I simply wish to check that the input string COULD be a validate path on the executing system.

So far I have been messing with the File class with no luck. I would expect the following to fail on my OSX machine but it doesn't:

File f = new File("!@£$%^&*()±§-_=+[{}]:;\"'|>.?/<,~`±");
System.out.println(f.getCanonicalPath());

Is there anything that will do this for me?

You can do it via regex: File path validation in javascript

Or by checking if the parent of the path exists: Is there a way in Java to determine if a path is valid without attempting to create a file?

Just note that the path depends on the OS: https://serverfault.com/questions/150740/linux-windows-unix-file-names-which-characters-are-allowed-which-are-unesc

Also, just because the path is valid, it doesn't mean the file can be written there. For example, in Linux, you need to be a super user to write to /usr/

You could choose to use regex to check the path. Regex would look like:

^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$

And an example can be seen here at Regexr . You can check this in Java using the String.matches(regex) function. An example below:

public static void main(String[] args) throws Exception {

    String regex = "^(?:[a-zA-Z]\\:|\\\\\\\\[\\w\\.]+\\\\[\\w.$]+)\\\\(?:[\\w]+\\\\)*\\w([\\w.])+$";
    String path = "c:\\folder\\myfile.txt";

    System.out.println(path.matches(regex));

}

( Note that the regex looks significantly longer due to having to escape the \\ characters ). Just call yourPathString.matches(regex) , and it will return true if it is a valid path.

If the path is valid, then at least one of the chain of parent files must exist. If no parent exists, then it must be invalid.

public static boolean isValidPath(File file) throws IOException {
    file = file.getCanonicalFile();

    while (file != null) {
        if (file.exists()) {
            return true;
        }

        file = file.getParentFile();
    }

    return false;
}

System.out.println(isValidPath(new File("/Users/something")));  // true (OS X)
System.out.println(isValidPath(new File("asfq34fawrf")));  // false

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