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?
If you are using the Gauva Library, you can directly use the getFileExtension() method to get the file extension. For example, String fileName = "Test. java"; String extension = Files.
Java 8 added some static methods to Files helper class as part of the Stream API, namely - Files. lines, Files. list, Files. walk, and Files.
Right-click the file. Select the Properties option. In the Properties window, similar to what is shown below, see the Type of file entry, which is the file type and extension.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With