Converting to a portable file path
public static String getPortableFilePath(String target)
{
Pattern ptr=Pattern.compile("[\\|/]+");
Matcher mtr=ptr.matcher(target);
return mtr.replaceAll(File.sep开发者_如何转开发arator);
}
public static void main(String[] args)
{
System.out.println(getPortableFilePath("C:///Program Files////Java\\jdk1.6.0_23/bin"));
}
In the above code I am trying to replace all the Forward and Backward slashes with the current systems File Separator. Code compiles fine when put into a class, but when executed it gives an array index out of bounds exception. Any guesses why?
The Exception:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(Unknown Source)
at java.util.regex.Matcher.appendReplacement(Unknown Source)
at java.util.regex.Matcher.replaceAll(Unknown Source)
at Files.getPortableFilePath
at Files.main
You method is (a) misnamed and (b) unnecessary. Misnamed because it doesn't return a portable file path, it returns a path for the current system; unnecessary because if you just use / everywhere Java will operate correctly on all platforms. There is never a need to use backslashes in Java filenames.
You need to get two backslashes through to the regex engine. Otherwise it will think you are escaping the next character. So use
"[\\\\/]+"
for the pattern string. That way it resolves to the pattern
[\\/]+
This is the problem with the string and the regex notation both using backslashes, and there being no way to skip the string interpolation stage.
And don’t use a vertical pipe in a square-bracket charclass: it is a literal there.
Thanks for the answers guys. Finally found the issue.
I replaced the
Pattern ptr=Pattern.compile("[\\\\/]+");
with
Pattern ptr=Pattern.compile("[\\\\\\\\|/]+");
as noted by tchrist, this was needed but still it didn't fix the error.
The error was fixed by replacing the
return mtr.replaceAll(File.separator);
line with
return mtr.replaceAll(File.separator+""+File.separator);
Since I am working in windows environment, the File.separator
returned "\" which itself worked as an escape character and the error was displayed, and that is why the original code worked fine on Jim Blackler's Mac because the File.separator
for him was not "\".
But still I could not make sense with the StringIndexoutOfBounds
exception, what does this exception had to do here.
精彩评论