Java I/O How to - Get file extension name








Question

We would like to know how to get file extension name.

Answer

 //  www .j  av  a  2s .c  o m


import java.io.File;

public class Main {
  public static void main(String[] argv) {
    getFileExtensionName(new File("a.txt"));
  }

  public static String getFileExtensionName(File f) {
    if (f.getName().indexOf(".") == -1) {
      return "";
    } else {
      return f.getName().substring(f.getName().length() - 3, f.getName().length());
    }
  }
}