Getting the file extension of the file is through Java using File class of Java i.e. probeContentType() method. The File class is Java’s representation of a file or directory pathname. The File class contains several methods for working with the pathname, deleting and renaming files, creating new directories, listing the contents of a directory, and determining several common attributes of files and directories.
probeContentType() Method
The probeContentType() is a method that comes predefined in the Java File class. The parameter to this method is passed the path of the file.
Parameters: A path of the file.
Return value: It returns a string(extension).
In Java, we can get the filename by –
File file = new File(“/home/mayur/GFG.java”);
String fileName = file.getName();
Below is the implementation of the problem statement:
Java
// Java Program to Get the File Extension import java.io.*; import java.nio.file.Files; public class GFG { public static void main(String[] args) { // File location File f = new File( "/home/mayur/GFG.java" ); // If file exists if (f.exists()) { String fileType = "Undetermined" ; String fileName = f.getName(); String extension = "" ; int i = fileName.lastIndexOf( '.' ); if (i > 0 ) { extension = fileName.substring(i + 1 ); } try { fileType = Files.probeContentType(f.toPath()); } catch (IOException ioException) { System.out.println( "Cannot determine file type of " + f.getName() + " due to following exception: " + ioException); } // Print Extension System.out.println( "Extension used for file is -> " + extension + " and is probably " + fileType); } else { System.out.println( "File does not exist!" ); } } } |
Output:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.