how to get only the file name from the given path............

example1:

String str1="C:\New Folder\My Data\kk.png"

From the above how can we get only the file kk.png

example2:

String str1="C:\New Folder\My Data\Java\Project\yy.bmp"

From the above how can we get only the file yy.bmp

Recommended Answers

Create a File object from the string, then use its getName() method. (Plus, this works for Linux too!).

Jump to Post

All 3 Replies

Create a File object from the string, then use its getName() method. (Plus, this works for Linux too!).

Member Avatar

Well... I would do it the way that JamesCherrill said,
but you could also do a search on the string from the end (looking for "\")
and do a substring() to get the file name.

Indeed you could. But rather than a hard-coded "\" you should use the delimiter (\ or /) appropriate for the OS the application is running on. There's a method that gives you that, but it's late and I can't remember exactly what it is. Goodnight.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.