我在后端数据库中有一个名为“path”的字段,它存储特定资源的路径。我的想法是让用户输入具有特定字符作为文件分隔符的路径(独立于操作系统),而不是为 Windows 路径存储大量反斜杠(转义)路径。
例如:
原始路径:
\\\\server\\share\\
数据库中的转义路径:
\\\\\\\\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: String index out of range: 1
我已经用其他字符进行了测试(例如:将 '%' 替换为 'q'),此函数工作正常,但 File.separator
和 "\\\\"
作为替换字符串不起作用。
我想知道有解决方法。或者更好、更简单、更优雅的解决方案。
最佳答案
我认为您应该将 URI 存储在数据库中,因为它们是独立于平台的。
例如,在Windows中:
File f = new File("C:\\temp\\file.txt");
System.out.println(f.toURI());
打印
file:/C:/temp/file.txt
在 Unix 上:
File f = new File("/path/to/file.txt");
System.out.println(f.toURI());
打印
file:/path/to/file.txt
将 URI 转换为文件:
File f = new File(new URI("file:/C:/temp/file.txt"));
关于java - 使用 java.regex 模式匹配器用 File.separator 替换字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4767456/