I read the directory path using system properties in java which will work both in windows and Linux based systems. Now I need to split this path with only a portion of the path to retrieve the rest. eg., C:\Test1\Test2\Test3\Test4
I need to split the above path with C:\Test1\Test2
and retrieve Test3\Test4
.
When I get this as string and use split
function that will give me error as illegal character because of "\"
character. If I plan to escape this character with "\\"
, this may not work in Linux box. Is there a way I can make this work both in Linux and Windows?
Use the below approach.
//Windows
String s = "C:\\Test1\\Test2\\Test3\\Test4";
String[] output = s.split(("/".equals(File.separator))? File.separator : "\\\\" );
//output: [C:, Test1, Test2, Test3, Test4]
//Linux:
String linuxString = "/Test1/Test2/Test3/Test4";
String[] linuxOutput = linuxString.split(("/".equals(File.separator))? File.separator : "\\\\" );
//output: [, Test1, Test2, Test3, Test4]
Hope this will solve the issue.
You are looking for File.separator
. Use it to split your string.
From the docs,
The system-dependent default name-separator character, represented as a string for convenience.
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