8

My problem is ::

From a string like "/usr/folder1/folder2/filename.ext"

  • I have to extract out file name only for display (filename.ext only).
    • My question would be how should I do it? Splitting on "/" and taking the last element is one way but doesn't smell nice to me.
  • I have to create a hyperlink which uses URI of the file as the destination. That will be something similar to file://domain.com/usr/folder1/folder2/filename.ext

I looked at URI and URL interfaces in java.net but could not find anything useful there.

Also, in some cases, my file path can have COMMA, SPACE etc (Windows folders). So, keep that in mind when giving any ideas.

Jagmal
  • 5,726
  • 9
  • 35
  • 35
  • The solution proposed is not universal. try http://stackoverflow.com/a/10944586/715269 instead. – Gangnus Jun 08 '12 at 07:26

3 Answers3

15

You could try something like this:

File file = new File("/usr/folder1/folder2/filename.ext");
System.out.println(file.getName());

I wasn't sure whether this would work if the file does not exist, but have just tried it and it appears to work OK.

trilobite
  • 306
  • 1
  • 3
  • The argument I needed to pass to the `File` constructor was a `Uri`, which was being rejected as an invalid argument. It's simple enough to turn the Uri into a string: `File file = new File(mImageUri.toString());` – Ash Ryan Arnwine Jan 07 '16 at 00:15
4

CommonsIO provides solutions for this problem: FilenameUtils.getName(), returns the file name + extension.

String filename = FilenameUtils.getName("/usr/folder1/folder2/filename.ext");
System.out.println(filename); // Returns "filename.ext"
schnatterer
  • 7,525
  • 7
  • 61
  • 80
3

You should have a look to the File class. Especially to the getName() method.

Nicolas
  • 24,509
  • 5
  • 60
  • 66