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?

3 comments:

  1. Use the following code
    f.getAbsolutePath().split(Pattern.quote(File.separator));

    ReplyDelete
  2. Thanks for such a great blog here. I was searching for something like this for quite a long time and at last, I’ve found it on your blog. It was definitely interesting for me to read about their market situation nowadays.
    artificial intelligence internship | best final year projects for cse | internship certificate online | internship for mba finance students | internship meaning in tamil

    ReplyDelete