Java – New Java 8 Way of Retrieving the File Extension

filefile-extensionjava

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?

Best Answer

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).

Related Question