Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split directory path with another path

Tags:

java

java-8

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?

like image 766
Raghavendra Bankapur Avatar asked Sep 06 '25 05:09

Raghavendra Bankapur


2 Answers

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.

like image 154
Sohail Ashraf Avatar answered Sep 09 '25 01:09

Sohail Ashraf


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.

like image 30
Mohamed Anees A Avatar answered Sep 09 '25 00:09

Mohamed Anees A