Simple Java parser
If you want to get a file extension from the file path you can try this code:
1 2 3 4 5 6 7 8 9 10 11 |
String fileName = "myFile.txt"; int lastIndexOfDot = fileName.lastIndexOf('.'); String fileExtension = null; if (lastIndexOfDot > 0) { fileExtension = fileName.substring(lastIndexOfDot+1); } System.out.println(fileExtension); |
lastIndexOf()
will give you the index of the last dot in a file name. The if statement guarantees that you will get a substring from dot to the end of a string (which usually is the file extension). Although, this solution is not perfect. It will work only with simple Windows-like file names. When it comes to the Unix ones like archive.tar.gz, it won’t work.
Apache Commons IO
If you are familiar with Apache Commons, you can use its FilenemUtils class. This contains the proper method named
getExtension()
which deal with the problems listed in the previous solution. Here’s how to use that:
1 2 3 |
String extension = FilenameUtils.getExtension("/path/to/file/fileName.txt"); |