使用java.regex模式匹配器将字符替换为File.separator

使用java.regex模式匹配器将字符替换为File.separator,java,regex,matcher,Java,Regex,Matcher,我在后端数据库中有一个名为“path”的字段,它存储到特定资源的路径。我的想法是让用户输入带有特定字符的路径作为文件分隔符(独立于操作系统),而不是为windows路径存储大量反斜杠(转义)路径 例如: 原始路径: \\\\server\\share\\ 以db为单位的转义路径: \\\\\\\\server\\\\share\\\\ 相反,我想要: %%server%share% 后来,我想用java的File.separator来代替它们。对于这项工作,我找到的最快的解决方案是使用ja

我在后端数据库中有一个名为“path”的字段,它存储到特定资源的路径。我的想法是让用户输入带有特定字符的路径作为文件分隔符(独立于操作系统),而不是为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 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("%%", "//");
}
输出

 %%server%%share%%
回来

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

我认为应该将URI存储在数据库中,因为它们与平台无关

例如,在窗口中

File f = new File("C:\\temp\\file.txt");
System.out.println(f.toURI());
File f = new File("/path/to/file.txt");
System.out.println(f.toURI());
印刷品

file:/C:/temp/file.txt
file:/path/to/file.txt
在Unix上:

File f = new File("C:\\temp\\file.txt");
System.out.println(f.toURI());
File f = new File("/path/to/file.txt");
System.out.println(f.toURI());
印刷品

file:/C:/temp/file.txt
file:/path/to/file.txt
将URI转换为文件:

File f = new File(new URI("file:/C:/temp/file.txt"));

我认为应该将URI存储在数据库中,因为它们与平台无关

例如,在窗口中

File f = new File("C:\\temp\\file.txt");
System.out.println(f.toURI());
File f = new File("/path/to/file.txt");
System.out.println(f.toURI());
印刷品

file:/C:/temp/file.txt
file:/path/to/file.txt
在Unix上:

File f = new File("C:\\temp\\file.txt");
System.out.println(f.toURI());
File f = new File("/path/to/file.txt");
System.out.println(f.toURI());
印刷品

file:/C:/temp/file.txt
file:/path/to/file.txt
将URI转换为文件:

File f = new File(new URI("file:/C:/temp/file.txt"));

String replaceStr=File.separator+File.separator这将起作用:)
stringreplacestr=File.separator+File.separator这将起作用:)