views:

1144

answers:

3

I have a String which provides an absolute path to a file (inlcuding the file name). I want to get just the filename. 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 getFile() - all though that would have been ideal if it was possible - as it's not necessarily an http:// prefix it could be c:/ or something similar.

+6  A: 
new File(fileName).getName();

or

int idx = fileName.replaceAll("\\", "/").lastIndexOf("/");
return idx >= 0 ? fileName.subString(idx + 1) : fileName;
kd304
You know, tight project due dates teaches you to type fast.
kd304
+5  A: 
new File(absolutePath).getName();
victor hugo
+3  A: 

Apache Commons IO provides the FilenameUtils class which gives you a pretty rich set of utility functions for easily obtaining the various components of filenames, although The java.io.File class provides the basics.

skaffman
Always use it. Can't complain.
Ravi Wallau