简体   繁体   English

确保路径字符串是有效的Java路径字符串

[英]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 \\) : 这就是我尝试确保属性文件中给出的路径是有效的Java路径(用\\\\而不是\\)的方式:

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. replaceAll需要RegExes,请改用replace

You can find the JavaDocs here 您可以在这里找到JavaDocs

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. File类用于拆分路径。 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. 在Java源代码中,是字符串或字符符号,反斜杠是转义字符,将下一个转换为特殊含义。 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: 如果您阅读特殊文本,请使用反斜杠转义(例如\\n换行),然后使用非正则表达式替换字符串:

// 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. 对于文件路径,只有最后一个才有意义,但不应该这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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