如何在Java中获取目录下所有jpg文件的列表?
File类的**String[] list(FilenameFilter filter)**方法返回一个字符串数组,其中包含当前(File)对象所表示路径中的所有文件和目录的名称。但是,返回的数组包含基于指定过滤器过滤的文件名。**FilenameFilter**是Java中的一个接口,只有一个方法。
accept(File dir, String name)
要根据扩展名获取文件名,请按如下方式实现此接口并将它的对象传递给上面指定的File类的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 {
//Creating a File object for directory
File directoryPath = new File("D:\ExampleDirectory");
//Creating filter for jpg files
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("List of the jpeg files in the specified directory:");
for(String fileName : imageFilesList) {
System.out.println(fileName);
}
}
}输出
List of the jpeg files in the specified directory: 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);
}
}输出
List of the jpeg files in the specified directory: cassandra_logo.jpg cat.jpg coffeescript_logo.jpg javafx_logo.jpg
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP