如何在Java中搜索带有文件扩展名的目录?
以下示例根据扩展名将文件打印在目录中-
示例
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 Demo { public static void main(String[] args) throws IOException { Stream<Path> path = Files.walk(Paths.get("D:\\ExampleDirectory")); System.out.println("PDF文件列表:"); path = path.filter(var -> var.toString().endsWith(".pdf")); path.forEach(System.out::println); path = Files.walk(Paths.get("D:\\ExampleDirectory")); System.out.println("JPG文件列表:"); path = path.filter(var -> var.toString().endsWith(".jpg")); path.forEach(System.out::println); path = Files.walk(Paths.get("D:\\ExampleDirectory")); System.out.println("文本文件列表:"); path = path.filter(var -> var.toString().endsWith(".txt")); path.forEach(System.out::println); path = Files.walk(Paths.get("D:\\ExampleDirectory")); System.out.println("字文件列表:"); path = path.filter(var -> var.toString().endsWith(".docx")); path.forEach(System.out::println); } }输出结果
PDF文件列表: D:\ExampleDirectory\demo1.pdf D:\ExampleDirectory\demo2.pdf JPG文件列表: D:\ExampleDirectory\sample_jpeg1.jpg D:\ExampleDirectory\sample_jpeg2.jpg 文本文件列表: D:\ExampleDirectory\sample1.txt D:\ExampleDirectory\sample2.txt D:\ExampleDirectory\sample3.txt 字文件列表: D:\ExampleDirectory\test1.docx D:\ExampleDirectory\test2.docx
以下示例根据扩展名在目录中打印PDF文件的名称-
示例
import java.io.File; import java.io.FilenameFilter; import java.io.IOException; public class MyExample{ 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(".pdf")) { return true; } else { return false; } } }; String imageFilesList[] = directoryPath.list(jpgFilefilter); System.out.println("指定目录中的jpeg文件列表:"); for(String fileName : imageFilesList) { System.out.println(fileName); } } }输出结果
指定目录中的jpeg文件列表: demo1.pdf demo2.pdf