how to split the string in java in Windows? I used Eg.
String directory=\"C:\\home\\public\\folder\";
String [] dir=direct.split(\"\\\");
split("\\")
A backlash is used to escape.
split()
function in Java accepts regular expressions. So, what you exactly need to do is to escape the backslash character twice:
String[] dir=direct.split("\\\\");
One for Java, and one for regular expressions.
It's because of the backslash. A backslash is used to escape characters. Use
split("\\")
to split by a backslash.
The syntax error is caused because the sing backslash is used as escape character in Java.
In the Regex '\'
is also a escape character that why you need escape from it either.
As the final result should look like this "\\\\"
.
But You should use the java.io.File.separator
as the split character in a path.
String[] dirs = dircect.split(Pattern.quote(File.separator));
thx to John
Please, don't split using file separators.
It's highly recommended that you get the file directory and iterate over and over the parents to get the paths. It will work everytime regardless of the operating system you are working with.
Try this:
String yourDir = "C:\\home\\public\\folder";
File f = new File(yourDir);
System.out.println(f.getAbsolutePath());
while ((f = f.getParentFile()) != null) {
System.out.println(f.getAbsolutePath());
}
final String dir = System.getProperty("user.dir");
String[] array = dir.split("[\\\\/]",-1) ;
String arrval="";
for (int i=0 ;i<array.length;i++)
{
arrval=arrval+array[i];
}
System.out.println(arrval);