I have a string that represents a path ... something like this:
/A/B/C/D/E/{id}/{file_name}.ext
The path structure could be different but in general I would like to retrieve last directory name (in the example {id}) before the file_name.
I would like to use Path java class.
Is there a simple and safe way to retrieve last directory name using Path class?
Path#getParent returns a path’s parent. You can then use Path#getFileName:
path.getParent().getFileName();
You could use getName() with File which is available
Reference : https://docs.oracle.com/javase/6/docs/api/java/io/File.html#getName%28%29
File f = new File("C:\\Dummy\\Folder\\MyFile.PDF");
System.out.println(f.getName());
Which returns you MyFile.PDF.
(or)
// Path object
Path path
= Paths.get("D:\\eclipse\\configuration"
+ "\\myconfiguration.conf");
// call getName(int i) to get
// the element at index i
Path indexpath = path.getName(path.getNameCount()-2);
// prints the name
System.out.println("Name of the file : " + indexpath);
Which prints myconfiguration.conf. Hope it helps !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With