วิธีที่ 1: ใช้ NIO.2 (Files.walk + Stream) - Java 8+
import java.io.IOException;
import java.nio.file.*;
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args) throws IOException {
Stream path = Files.walk(Paths.get("D:\\ExampleDirectory"));
System.out.println("List of PDF files:");
path.filter(p -> p.toString().endsWith(".pdf")).forEach(System.out::println);
path = Files.walk(Paths.get("D:\\ExampleDirectory"));
System.out.println("List of JPG files:");
path.filter(p -> p.toString().endsWith(".jpg")).forEach(System.out::println);
path = Files.walk(Paths.get("D:\\ExampleDirectory"));
System.out.println("List of text files:");
path.filter(p -> p.toString().endsWith(".txt")).forEach(System.out::println);
path = Files.walk(Paths.get("D:\\ExampleDirectory"));
System.out.println("List of word files:");
path.filter(p -> p.toString().endsWith(".docx")).forEach(System.out::println);
}
}
วิธีที่ 2: ใช้ FilenameFilter (Legacy IO)
import java.io.*;
public class MyExample {
public static void main(String args[]) throws IOException {
File directoryPath = new File("D:\\ExampleDirectory");
FilenameFilter pdfFilter = (dir, name) -> name.toLowerCase().endsWith(".pdf");
String[] pdfFiles = directoryPath.list(pdfFilter);
System.out.println("List of PDF files:");
for (String f : pdfFiles) System.out.println(f);
}
}
ผลลัพธ์ตัวอย่าง
List of PDF files:
D:\ExampleDirectory\demo1.pdf
D:\ExampleDirectory\demo2.pdf
List of JPG files:
D:\ExampleDirectory\sample_jpeg1.jpg
D:\ExampleDirectory\sample_jpeg2.jpg
สรุป
- Files.walk + Stream: ทันสมัย รองรับ Recursive, Functional Style
- FilenameFilter: Legacy ใช้กับ File.list() ไม่ Recursive (เฉพาะ Directory นั้นๆ)
- ทั้งสองกรองด้วย
endsWith(".ext") (ควร .toLowerCase() เพื่อ Case-insensitive)