J
jayharris
I'm trying to write a method that strips excess file separator
characters from a file path, so it would get something like this as
input: C:\\\Documents and Settings\\My Documents\\\\\Work\\\ and return
something more like this: C:\Documents and Settings\My Documents\Work\
My code looks like this:
private String getCorrectPath(String input) {
char fs = File.separatorChar;
String newInput;
try {
String regex = (Character.isLetter(fs) ? String.valueOf(fs) : "\\"
+ fs) + "{2,}";
newInput = input.replaceAll(regex, String.valueOf(fs))
}
catch(Exception e) {
return null;
}
return newInput;
}
This seems to work fine for something like Unix, but whenever I run it
on Windows, where the file separator is the same as the quoting
character, I get the following exception:
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 java.lang.String.replaceAll(Unknown Source)
Can anybody help me figure out what's going on?
Thanks,
Jay
characters from a file path, so it would get something like this as
input: C:\\\Documents and Settings\\My Documents\\\\\Work\\\ and return
something more like this: C:\Documents and Settings\My Documents\Work\
My code looks like this:
private String getCorrectPath(String input) {
char fs = File.separatorChar;
String newInput;
try {
String regex = (Character.isLetter(fs) ? String.valueOf(fs) : "\\"
+ fs) + "{2,}";
newInput = input.replaceAll(regex, String.valueOf(fs))
}
catch(Exception e) {
return null;
}
return newInput;
}
This seems to work fine for something like Unix, but whenever I run it
on Windows, where the file separator is the same as the quoting
character, I get the following exception:
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 java.lang.String.replaceAll(Unknown Source)
Can anybody help me figure out what's going on?
Thanks,
Jay