问题
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