Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve last level directory name from path

Tags:

java

path

parsing

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?

like image 644
Safari Avatar asked Jan 23 '26 19:01

Safari


2 Answers

Path#getParent returns a path’s parent. You can then use Path#getFileName:

path.getParent().getFileName();
like image 161
Konrad Rudolph Avatar answered Jan 25 '26 08:01

Konrad Rudolph


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 !

like image 33
Tom Taylor Avatar answered Jan 25 '26 08:01

Tom Taylor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!