Get file extension name in Java


The file extension is the suffix that is attached to the computer file and it denotes the format of the file. A program that demonstrates getting the file extension name is given as follows −

Example

 Live Demo

import java.io.File;
public class Demo {
   private static String fileExtension(File file) {
      String name = file.getName();
      if(name.lastIndexOf(".") != -1 && name.lastIndexOf(".") != 0)
         return name.substring(name.lastIndexOf(".") + 1);
      else
         return "";
   }
   public static void main(String[] args) {
      File file = new File("demo1.txt");
      System.out.println("The file extension is: " + fileExtension(file));
   }
}

The output of the above program is as follows −

Output

The file extension is: txt

Now let us understand the above program.

The method fileExtension() returns the file extension and it takes a single parameter i.e. the File class object. A code snippet that demonstrates this is given as follows −

private static String fileExtension(File file) {
   String name = file.getName();
   if(name.lastIndexOf(".") != -1 && name.lastIndexOf(".") != 0)
      return name.substring(name.lastIndexOf(".") + 1);
   else
      return "";
}

The method main() calls the method fileExtension() and prints the file extension returned. A code snippet that demonstrates this is given as follows −

public static void main(String[] args) {
   File file = new File("demo1.txt");
   System.out.println("The file extension is: " + fileExtension(file));
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

466 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements