Split directory path with another path

Viewed 384

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?

4 Answers

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.

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.

The pattern passed to String.split has the regular expression syntax, thus the java.util.regex package is the place to look for additional tools for dealing with them, like quoting a string to enforce literal matching.

So a solution only using system properties and string operations would look like

String path=System.getProperty("your.property"), sep=System.getProperty("file.separator");
for(String s: path.split(Pattern.quote(sep)))
    System.out.println(s);

However, there is no reason not to use the dedicated APIs:

Path path = Paths.get(System.getProperty("your.property"));
if(path.isAbsolute()) System.out.println(path.getRoot());
for(Path p: path)
    System.out.println(p);

Note that this also handles root paths correctly, i.e. on Windows, the root of a drive is like C:\, not C:, and on Linux, the root is /, not an empty string, and both cases are not handled correctly when just splitting at the separator chars.

Even before Java 7, there was an API that could handle this:

File path = new File(System.getProperty("your.property"));
for(File f = path; f != null; f = f.getParentFile())
    System.out.println(f.getName().isEmpty()? f.getPath(): f.getName());

though the code will iterate the elements in the opposite order.


Note, how simple your specific task of splitting at two levels above the path becomes with the dedicated API:

Path path = Paths.get(System.getProperty("your.property"));
Path first = path.getParent().getParent(), second = first.relativize(path);

System.out.println("first: "+first);
System.out.println("second: "+second);

You can use separator when you are building a file path.

Use java.io.File.separator

Related