【问题标题】:Replacing character with File.separator using java.regex Pattern Matcher使用 java.regex Pattern Matcher 用 File.separator 替换字符
【发布时间】: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; 这会起作用:)

标签: java regex matcher


【解决方案1】:

我认为您应该将 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"));

【讨论】:

    【解决方案2】:
     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("%%", "//");
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-10
      • 1970-01-01
      • 2011-09-24
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-25
      • 1970-01-01
      相关资源
      最近更新 更多