I work with directories and files in Linux. For example, I have the following piece of code:

File f = new File("/media/yevhenii/Local disk D/Books"); System.out.println(f.getAbsolutePath()); 

The result is a full path, like "/ media / yevhenii / Local disk D / Books". How can one separate the first two catalogs (ie / media / yevhenii /) from the steel part? I thought through substring (), but if I have a different path (for example / media / yevhenii / Local disk D / Books / Books2) then substring () will work crookedly. Those. the point is that for any length of paths the first two directories are deleted. Thank you in advance.

Closed due to the fact that off-topic participants LEQADA , Vladimir Glinskikh , Axifive , Niki-Timofe , Bald December 8, '15 at 3:31 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • "The question is caused by a problem that is no longer reproduced or typed . Although similar questions may be relevant on this site, solving this question is unlikely to help future visitors. You can usually avoid similar questions by writing and researching a minimum program to reproduce the problem before publishing the question. " - LEQADA, Vladimir Glinskikh, Axifive, Niki-Timofe, Bald
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • And if there are only 2? - LEQADA

2 answers 2

Did not check under Linux, but should work:

Starting from 1.7, Java has a new API for working with java.nio.file files. You can do the following:

 File f = new File("/home/user/somedir/somefile" ); Path p = f.toPath(); // переход на новое api System.out.println( p ); // вывод: /home/user/somedir/somefile // вернет путь p относительно /home/user Path rel = Paths.get( "/home/user/" ).relativize( p ); System.out.println( rel ); // вывод: somedir/somefile // вернет часть пути от третьего элемента до конца Path subpath = p.subpath( 2, p.getNameCount() ); System.out.println( subpath ); // вывод: somedir/somefile 

Path can be turned back into File by the path.toFile() method, but new classes and methods accept Path , for example java.nio.file.Files.copy(Path source, Path target, CopyOption... options) , or java.nio.file.Files.readAllLines(Path path): List<String> .

  • And if, for example, I take a directory tree and I need to remove all previous directories from the tree? For example: instead of output: Local Disk D / Books Local Disk D / Books / Books2 I need to get output in this form: Local Disk D / Books / Books2 / - Evhenii Vasylenko
  • path.getFileName() returns the last element of the path. path.getName(int index) returns the element of the path by number, 0 - closest to the root. - zRrr

The problem is solved very simply: with the help of substring()

Like:

  f.getAbsolutePath().substring(16) 
  • Are the first two directories always the same? - LEQADA
  • Yes. In Linux yes - Evhenii Vasylenko