FilenameFilter

The listFiles method with parameters supports filtering of sub-files, and only obtains file objects that need to meet the conditions

The FilenameFilter interface contains an accept(File dir, String name) method, which is used to iterate over all subdirectories or files of the specified File. If the method returns true, the list method will get the directory or file

@FunctionalInterface 
public interface FilenameFilter {
    
     
	//参数dir是文件所在的目录,name是文件名称 
	boolean accept(File dir, String name); //当返回值为true时表示要,否则不要 
}

public class Test {
    
     
	public static void main(String[] args) {
    
     
		File ff=new File("c:/windows"); 
		File[] children=ff.listFiles(new MyFileNameFilter()); 
		for(File temp:children) 
			System.out.println(temp.getAbsolutePath()); 
	}
	static class MyFileNameFilter implements FilenameFilter{
    
     
		public boolean accept(File dir, String name) {
    
     
			return name.endsWith(".exe"); 
		} 
	} 
}

Anonymous inner class writing: recommended writing

public class Test {
    
     
	public static void main(String[] args) {
    
     
		File ff=new File("c:/windows"); 
		File[] children=ff.listFiles(new FilenameFilter() {
    
     
			public boolean accept(File dir, String name) {
    
     
				return name!=null && name.endsWith(".exe"); 
			} 
		}); 
		for(File temp:children) 
			System.out.println(temp.getAbsolutePath()); 
	} 
}

Guess you like

Origin blog.csdn.net/qq_43480434/article/details/113357368