文件过滤的三种基本操作

it2026-08-28  4

Java文件的过滤简单使用

方法1:遍历的同时进行判断,最差劲的做法!

//找出D:\\www下的.jpg文件 import java.io.*; public class Text { public static void main(String[] args) throws Exception { File f = new File("D:\\www"); read(f); } public static void read(File file) { File[] fi = file.listFiles(); for(File f:fi) { if(f.isDirectory()) { read(f); }else { if(f.getName().endsWith(".jpg")) { System.out.println(f.getName()); } } } } }

方法2:实现接口FileFilter接口

import java.io.*; public class Text { public static void main(String[] args) throws Exception { File f = new File("D:\\www"); read(f); } public static void read(File file) { File[] fi = file.listFiles(new FileFilter() { //实现FileFilter接口 @Override public boolean accept(File pathname) { if(pathname.isDirectory()) { read(pathname); } return pathname.getName().endsWith(".jpg"); } }); for(File f:fi) { System.out.println(f.getName()); } } }

方法3:实现FileNameFilter

import java.io.*; public class Text { public static void main(String[] args) throws Exception { File f = new File("D:\\www"); read(f); } public static void show2(File file) { String[] arr = file.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { //此时我们要判断一下是否为目录 File f = new File(dir,name); if(f.isDirectory()) { show2(f); } return name.endsWith(".txt"); } }); for(String ss: arr) { System.out.println(ss); } } }
最新回复(0)