Ankur Ankur - 1 year ago 82
Java Question

Get file name from a file location in Java

I have a

that provides an absolute path to a file (including the file name). I want to get just the file's name. What is the easiest way to do this?

It needs to be as general as possible as I cannot know in advance what the URL will be. I can't simply create a URL object and use
- all though that would have been ideal if it was possible - as it's not necessarily an
prefix it could be c:/ or something similar.

Answer Source
new File(fileName).getName();


int idx = fileName.replaceAll("\\", "/").lastIndexOf("/");
return idx >= 0 ? fileName.substring(idx + 1) : fileName;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download