使用java.regex Pattern Matcher替换File.separator中的字符

时间:2011-01-22 11:08:26

标签: java regex matcher

我在后端数据库中有一个名为'path'的字段,它存储了某个资源的路径。我的想法是让用户输入具有特定字符的路径作为文件分隔符(独立于操作系统),而不是存储大量用于Windows路径的反向(转义)路径。

例如:

原始路径:

\\\\server\\share\\

在db中使用转义路径:

\\\\\\\\server\\\\share\\\\

我希望:

%%server%share%

后来我想用真实的东西替换那些带有java File.separator的东西。对于这项工作,我发现最快的解决方案是使用java.regex Pattern Matcher。

这项工作的职责是:

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"\\\\"因为替换字符串不起作用。

我想知道它有解决方法。或者更好,更简单,更优雅的解决方案。

2 个答案:

答案 0 :(得分:3)

我认为你应该在你的数据库中存储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"));

答案 1 :(得分:0)

 String str = " \\server\\share\\";
 String result = str.replaceAll("\\\\", "%%");
 System.out.println(result);

<强>输出

 %%server%%share%%

并返回

String path=null;
if (File.separator.equals("\\")) {
    path = result.replaceAll("%%", "\\\\");
} else {
    path = result.replaceAll("%%", "//");
}