How to Get File Extension in Java - RameshMF/java-io-guide GitHub Wiki
In this example, we will check the file extensions such as txt, docx,pdf etc.
Get File Extension Example
- Let's use lastIndexOf() method of String class to find the index of last character ".".
- First check whether the file has extention or not.
- Use substring() method to get extension of the file.
package com.javaguides.javaio.fileoperations.fileexamples;
import java.io.File;
/**
* This Java program demonstrates how to get file extension in Java example.
* @author javaguides.net
*/
public class GetFileExtensionExample {
private static String getFileExtension(File file) {
String fileName = file.getName();
if (fileName.lastIndexOf('.') != -1 && fileName.lastIndexOf('.') != 0) {
return fileName.substring(fileName.lastIndexOf('.') + 1);
} else {
return "File don't have extension";
}
}
public static void main(String[] args) {
File file = new File("sample.txt");
System.out.println(getFileExtension(file));
File file1 = new File("sample");
System.out.println(getFileExtension(file1));
File file2 = new File("sample.docx");
System.out.println(getFileExtension(file2));
}
}
Output of the above program is:
txt
File don't have extension
docx
Reference
https://docs.oracle.com/javase/8/docs/api/java/io/File.html https://docs.oracle.com/javase/8/docs/api/java/lang/String.html