简体   繁体   中英

Making sure a path string is a valid java path string

This is how i try to make sure a path given in a property file is a valid java path (with \\\\ instead of \\) :

String path = props.getProperty("path");
if (path.length()>1) path=path.replaceAll("\\\\", "\\");
if (path.length()>1) path=path.replaceAll("\\", "\\\\");

in the first replace im making sure that if the path already valid (has \\\\ instead of \\) then it wont get doubled to \\\\\\\\ instead of \\\\ in the second replace...

anyway i get this weird exception :

java.lang.StringIndexOutOfBoundsException: String index out of range: 1
    at java.lang.String.charAt(Unknown Source)
    at java.util.regex.Matcher.appendReplacement(Unknown Source)
    at java.util.regex.Matcher.replaceAll(Unknown Source)
    at java.lang.String.replaceAll(Unknown Source)
    at com.hw.Launcher.main(Launcher.java:56)

can anyone tell why?!

replaceAll expects RegExes, use replace instead.

You can find the JavaDocs here

If you want to be sure the path is valid, how about trying

    File f = new File("c:\\this\\that");
    f.getCanonicalPath();

The File class is made for taking apart paths. It's probably the best way to verify that a path is valid.

(Let me spell it out for newbies too.)

If you have a text file or a String, normally only a single backslash should occur.

In java source code, a string or character denotation, backslash is the escape character, transforming the next one into a special meaning. Backslash itself should be given doubled, as \\\\ . The string value itself will have only one backslash character.

If you read special text, using backslash escaping (like \\n for a line break), then use the non-regex replace of strings:

// First escapes of other:
path = path.replace("\\n", "\n"); // Text `\n` -> linefeed
path = path.replace("\\t", "\t"); // Text `\t` -> tab
// Then escape of backslash:
path = path.replace("\\\\", "\\"); // Text `\\` -> backslash

For file paths only the last might make sense, but it should not have been needed.

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