如何在Java中根据文件扩展名过滤文件并显示文件名?
名为File的java.io包中的类表示系统中的文件或目录(路径名)。此类提供了各种方法来对文件/目录执行各种操作。
要获取目录中所有现有文件的列表,此类提供了五种不同的方法来获取特定文件夹中所有文件的详细信息:
- String[] list()
- File[] listFiles()
- String[] list(FilenameFilter filter)
- File[] listFiles(FilenameFilter filter)
- File[] listFiles(FileFilter filter)
其中,**String[] list(FilenameFilter filter)**方法返回一个字符串数组,其中包含当前(File)对象所表示的路径中所有文件和目录的名称。但是,返回的数组包含根据指定过滤器过滤的文件名。
**FilenameFilter**是Java中的一个接口,带有一个方法。
accept(File dir, String name)
要根据扩展名获取文件名,请按如下方式实现此接口并将它的对象传递给文件类的上面指定的list()方法。
示例
假设我们在D目录中有一个名为ExampleDirectory的文件夹,其中包含7个文件和2个目录,如下所示:

以下Java程序分别打印路径D:\ExampleDirectory中文本文件和jpeg文件的名称。
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
public class ListOfFiles {
public static void main(String args[]) throws IOException {
//Creating a File object for directory
File directoryPath = new File("D:\ExampleDirectory");
FilenameFilter textFilefilter = new FilenameFilter(){
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".txt")) {
return true;
} else {
return false;
}
}
};
FilenameFilter jpgFilefilter = new FilenameFilter(){
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".jpg")) {
return true;
} else {
return false;
}
}
};
//List of all the text files
String textFilesList[] = directoryPath.list(textFilefilter);
System.out.println("List of the text files in the specified directory:");
for(String fileName : textFilesList) {
System.out.println(fileName);
}
String imageFilesList[] = directoryPath.list(jpgFilefilter);
System.out.println("List of the jpeg files in the specified directory:");
for(String fileName : imageFilesList) {
System.out.println(fileName);
}
}
}输出
List of the text files in the specified directory: SampleFile1.txt SampleFile2.txt SapmleFile3.txt List of the jpeg files in the specified directory: cassandra_logo.jpg cat.jpg coffeescript_logo.jpg javafx_logo.jpg
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP