Replacing character with File.separator using java.regex Pattern Matcher

左心房为你撑大大i 提交于 2019-12-12 02:40:07

问题


I have a field called 'path' in back end database, which stores the path to certain resource. Instead of storing lots of backslashed (escaped) path for windows path, my idea is to let user enter the path with certain character as file separator (independent of OS).

For example:

original path:

\\\\server\\share\\

with escaped path in db:

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

instead I want:

%%server%share%

and later I wanted to replace those with java's File.separator for the real thing. For this job, the quickest solution I found is to use the java.regex Pattern Matcher.

My function for this job is:

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;
}

but the same File.separator which was supposed to save life is creating trouble with

java.lang.StringIndexOutOfBoundsException: String index out of range: 1

I have tested with other characters (for example: replace '%' with 'q') and this function works fine but File.separator and "\\\\" as replace string is not working.

I like to know it there is workaround for this. Or better, easier and elegant solution.


回答1:


I think you should store URIs in your database because they are platform independent.

Example, in Windows:

File f = new File("C:\\temp\\file.txt");
System.out.println(f.toURI());

prints

file:/C:/temp/file.txt

On Unix:

File f = new File("/path/to/file.txt");
System.out.println(f.toURI());

prints

file:/path/to/file.txt

To convert a URI to File:

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



回答2:


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

Output

 %%server%%share%%

and back

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


来源:https://stackoverflow.com/questions/4767456/replacing-character-with-file-separator-using-java-regex-pattern-matcher

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!