Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 594
mike Avatar asked Jun 18 '15 11:06

mike


People also ask

How do I get the file extension of a file in Java?

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.

Which method is added in Java 8 for file operation?

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.

How do you find the file extension?

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.


1 Answers

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

like image 156
Pshemo Avatar answered Sep 21 '22 12:09

Pshemo