English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn how to get the file extension of 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:
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