【发布时间】:2011-06-13 15:20:33
【问题描述】:
我在后端数据库中有一个名为“路径”的字段,它存储特定资源的路径。我的想法是让用户以特定字符作为文件分隔符(独立于操作系统)输入路径,而不是为 Windows 路径存储大量反斜杠(转义)路径。
例如:
原路径:
\\\\server\\share\\
在 db 中有转义路径:
\\\\\\\\server\\\\share\\\\
我想要:
%%server%share%
后来我想用 java 的File.separator 替换那些真正的东西。对于这项工作,我发现最快的解决方案是使用 java.regex 模式匹配器。
我的职责是:
private String convertToRealPathFromDB(String pth) {
String patternStr = "%";
String replaceStr = File.separator;
String convertedpath;
//Compile regular expression
Pattern pattern = Pattern.compile(patternStr); //pattern to look for
//replace all occurance of percentage character to file separator
Matcher matcher = pattern.matcher(pth);
convertedpath = matcher.replaceAll(replaceStr);
System.out.println(convertedpath);
return convertedpath;
}
但本应挽救生命的同一个 File.separator 却给
带来麻烦java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:1
我已经用其他字符进行了测试(例如:用 'q' 替换 '%')并且这个函数可以正常工作,但是 File.separator 和 "\\\\" 因为替换字符串不起作用。
我想知道有解决方法。或者更好、更简单、更优雅的解决方案。
【问题讨论】:
-
String replaceStr = File.separator + File.separator;这会起作用:)