Is there a new Java 8 way of retrieving the file extension?

mike picture mike · Jun 18, 2015 · Viewed 26.6k times · Source

What I did up until now is following:

String fileName = "file.date.txt";
String ext = fileName.substring(fileName.lastIndexOf('.') + 1);

System.out.printf("'%s'%n", ext); // prints: 'txt'

Is there a more convenient way in Java 8?

Answer

Pshemo picture Pshemo · Jun 18, 2015

No there is no more efficient/convenient way in JDK, but many libraries give you ready methods for this, like Guava: Files.getFileExtension(fileName) which wraps your code in single method (with additional validation).