How do I get the file extension of a file in Java?

Here some Example to explain how to get the file extension in java.

  • First Example with FilenameUtils:
package com.nourit.javaIO;

import org.apache.commons.io.FilenameUtils;

public class GetFileExtensionExample {

  public static void main(String[] args) {
    String fileext1 = FilenameUtils.getExtension("/nourit.ai"); // returns "txt"
    String fileext2 = FilenameUtils.getExtension("D:/tmp/nourit.txt"); // returns "exe"
    System.out.println("File extension 1 is: "+ fileext1);
    System.out.println("File extension 2 is: "+ fileext2);
  }
}

Second Exapmle:

package com.nourit.javaIO;

import java.io.File;

public class GetFileExtensionExample1 {

  public static void main(String[] args) {
    File file1 = new File("nourit.ai");
    File file2 = new File("D:/tmp/nourit.txt");
    String name1 = file1.getName();
    String name2 = file2.getName();
    String file1Ext = name1.substring(name1.lastIndexOf(".") + 1);
    String file2Ext =name2.substring(name2.lastIndexOf(".") + 1);
    System.out.println("File extension 1 is: "+ file1Ext);
    System.out.println("File extension 2 is: "+ file2Ext);
  }
}
  • Third Example with REGEX (regular) Pattern.compile(„(.*)\\.(.*)“)
package com.nourit.javaIO;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GetFileExtensionExample2 {

  static final Pattern PATTERN = Pattern.compile("(.*)\\.(.*)");
  public static void main(String[] args) {
    File file1 = new File("nourit.ai");
    File file2 = new File("D:/tmp/nourit.txt");

    String path1 = file1.getPath();
    Matcher m1 = PATTERN.matcher(path1);
    if (m1.find()) {
//			System.out.println("File path/name: " + m1.group(1));
      System.out.println("File extension 1 is: "+ m1.group(2));
    }
    String path2 = file2.getPath();
    Matcher m2 = PATTERN.matcher(path2);
    if (m2.find()) {
//			System.out.println("File path/name: " + m2.group(1));
      System.out.println("File extension 2 is: "+ m2.group(2));
    }
  }
}

Output:

File extension 1 is: ai
File extension 2 is: txt

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*