File 类的String[]list(FilenameFilter filter) 方法返回一个 String 数组,其中包含当前 (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 Sample{ public static void main(String args[]) throws IOException { //为目录创建文件对象 File directoryPath = new File("D:\ExampleDirectory"); //为 jpg 文件创建过滤器 FilenameFilter jpgFilefilter = new FilenameFilter(){ public boolean accept(File dir, String name) { String lowercaseName = name.toLowerCase(); if (lowercaseName.endsWith(".jpg")) { return true; } else { return false; } } }; String imageFilesList[] = directoryPath.list(jpgFilefilter); System.out.println("指定目录下的jpeg文件列表:"); for(String fileName : imageFilesList) { System.out.println(fileName); } } }输出结果
指定目录下的jpeg文件列表: cassandra_logo.jpg cat.jpg coffeescript_logo.jpg javafx_logo.jpg
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; public class Example { public static void main(String[] args) throws IOException { Stream<Path> path = Files.walk(Paths.get("D:\ExampleDirectory")); path = path.filter(var -> var.toString().endsWith(".jpg")); path.forEach(System.out::println); } }输出结果
指定目录下的jpeg文件列表: cassandra_logo.jpg cat.jpg coffeescript_logo.jpg javafx_logo.jpg