The use of java file filter

Foreword:

java.io.FileFilter (filter interface)
boolean accept(File pathname)

The File class provides the following methods to use filters:
public File[] listFiles(FileFilter filter)

code show as below:

//filter class
class filter1 implements FileFilter{

	@Override
	public boolean accept(File pathname) {
		// TODO Auto-generated method stub
		if(pathname.isFile()&&pathname.exists()){
			String name = pathname.getName();
			if(name.endsWith(".box")){
				return true;
			}
		}
		return false;
	}
	
}

// The general principle of the method of listFiles with parameters

//public File[] listFiles(FileFilter filter){
//// Get all files or folders in the specified directory
//	File[] all = listFiles();
//	File temp;
//	for(int i = 0;i<all.length;i++){
//		if(filter.accept[all[i]]){
//			temp[j] = all[i];
//		}
//	}
//	return temp;
//}


public class FilterUse {
	public static void main(String[] args) {
// usage of file filter
		File f = new File("D:\\dev-machine");
// Get all files or folders in the specified directory
		File[] ffs = f.listFiles(new filter1());
		
// Filter out files with the suffix .box
		for (File file : ffs) {
			System.out.println(file.getName());
		}
	}
}

 Its internal principle structure diagram is roughly as follows:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325254286&siteId=291194637