Split directory path with another path

Raghavendra Bankapur :

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?

Sohail :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=322721&siteId=1