English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented Programming(I)

Java Object-Oriented Programming(II)

Java Object-Oriented Programming(III)

Java Exception Handling

Java List(List)

Java Queue(Queue)

Java Map Collection

Java Set Collection

Java Input Output (I)/O)

Java Reader/Writer

Java Other Topics

Java Program to Get File Extension

Java Examples Comprehensive

In this example, we will learn how to get the file extension of Java.

Example1:获取文件扩展名的Java程序

import java.io.File;
class Main {
  public static void main(String[] args) {
    File file = new File("Test.java");
    //将文件名转换为字符串
    String fileName = file.toString();
    int index = fileName.lastIndexOf('.');
    if(index > 0) {
      String extension = fileName.substring(index + 1);
      System.out.println("File extension is " + extension);
    }
  }
}

In the above example,

  • file.toString() - Converts the File object to a string.

  • fileName.lastIndexOf('.') - Returns the last occurrence position of the character. Since all file extensions are prefixed with"."as the starting point,we use the character"."

  • fileName.substring() -  Returns the character"."The string after

Recommended reading:

Example2:获取目录中存在的所有文件的文件扩展名

Now, let's assume we want to get the file extensions of all files existing in the directory. We can loop through the above process.

import java.io.File;
class Main {
  public static void main(String[] args) {
    File directory = new File("Directory");
    //列出目录中存在的所有文件
    File[] files = directory.listFiles();
    System.out.println("文件\t\t\t扩展名");
    for(File file : files) {
      //将文件名转换为字符串
      String fileName = file.toString();
      int index = fileName.lastIndexOf('.');
      if(index > 0) {
        String extension = fileName.substring(index + 1);
        System.out.println(fileName + "\t" + extension);
      }
    }
  }
}

输出结果

文件                   扩展名
Directory\file1.txt     txt
Directory\file2.svg     svg
Directory\file3.java    java
Directory\file4.py      py
Directory\file5.html    html

NoteThe output of the program depends on the directory you use and the files contained in that directory.

  • If you are using the Guava library, you can directly use the getFileExtension() method to obtain the file extension. For example,

    String fileName = "Test.java";
    String extension = Files.getFileExtension(fileName);
  • And, Apache Commons IO also provides the FilenameUtils class, which provides the getExtension method to obtain the file extension.

    String extension = FilenameUtils.getExtension("file.py") // returns py

Java Examples Comprehensive