Extract path parts in Java

I have a file path similar to this:

/home/Dara/Desktop/foo/bar/baz/qux/file.txt 

In Java, I would like to get top two folders. I.e. baz/qux regardless of the length of the file path or operating system (file path delimiters such as / : and \ ). I tried using the subpath() method in Paths , but I cannot find a general way to get the length of the file path.

+4
source share
5 answers

Not really yet, you guessed the direction:

 File parent = file.getParentFile(); File parent2 = parent.getParentFile(); parent2.getName() + System.getProperty("path.separator") + parent.getName() 

Another option:

 final int len = path.getNameCount(); path.subpath(len - 3, len - 1) 

Edit: You need to either check len or catch an IllegalArgumentException to make your code more reliable.

+7
source

The getNameCount() and getName(int index) of java.nio.Path methods should help you:

 File f = new File("/home/Dara/Desktop/foo/bar/baz/qux/file.txt"); Path p = f.toPath(); int pathElements = p.getNameCount(); String topOne = p.getName(pathElements-2).toString(); String topTwo = p.getName(pathElements-3).toString(); 

Note that the result of getNameCount() must be validated before using it as an index for getName() .

+4
source

You can simply split string or use StringTokenizer .

+2
source

Using subpath and getNameCount.

  Path myPath = Paths.get("/home/Dara/Desktop/foo/bar/baz/qux/file.txt"); Path subPath = myPath.subpath(myPath.getNameCount() -3, myPath.getNameCount() -1); 
+2
source

File.getParent() will delete the file name.

And you get the path separator: System.getProperty("file.separator") .

Then you can use String.split() to get each part of the path.

+1
source

Source: https://habr.com/ru/post/1469245/


All Articles