Saturday, April 30, 2011

How to split on "\" or backslash in Java

Suppose we have the following code:-
String  path = "C:\\Users\\Ken";

Let's try to  populate the folderNames array with "C:", "Users" and "Ken" by spliting on "\" - backslash


String[] folderNames= path.split("\\");

BUT We get the following exception:-
/*
Exception in thread "main" 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.(Unknown Source) at java.util.regex.Pattern.compile(Unknown Source) at java.lang.String.split(Unknown Source) at java.lang.String.split(Unknown Source)
*/
Instead use the following:-
String[] folderNames= f.getAbsolutePath().split("\\\\");
Any questions?