The following snippet works fine under linux but gives me error under windows (which is very weird since jvm/jdk is supposed to be OS-agnostic).
File f = ...
String[] split = f.getPath().split(File.separator);
Here is the error:
java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.split(Unknown Source)
at java.lang.String.split(Unknown Source)
any idea what is wrong?
You should consider using the Path class introduced with java.nio. It works even if you mix the separators. This code:
Path path = Paths.get("c:\\a\\with spaces/b");
for(Iterator<Path> it= path.iterator(); it.hasNext();) {
System.out.println(it.next());
}
prints:
a
with spaces
b
The problem is that the backslash is a special character using regexes (escape character for other special characters). You should use
String[] split = f.getPath().split("\\\\");
in order to split by the sign \
.
I see the problem you have if you want to keep this platform independant. In that case you could do something like this:
String splitter = File.separator.replace("\\","\\\\");
String[] split = abc.split(splitter);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With