IO-输入输出流 (文件查询操作)

java文件操作 (封装对文件迭代查询等功能)

public class ListFileUtil {

   //指定目录下的所有文件信息
   public static void listAllFiles(String dirName){
      if(!dirName.endsWith(File.separator)){
    	  dirName = dirName + File.separator;
    	  System.out.println(dirName);
      }
      File dirFile = new File(dirName);
	  if(!dirFile.exists()||!dirFile.isDirectory()){
		System.out.println("找不到目录"+dirName);
	  }
	  
	  File[] files = dirFile.listFiles();
	  if(files.length > 0){
		 for(int i=0;i<files.length;i++){
			 if(files[i].isFile()){
				 System.out.println(files[i].getAbsolutePath()+"是文件");
				 
			 }else if(files[i].isDirectory()){
				 System.out.println(files[i].getAbsolutePath() + "是目录");
				 listAllFiles(files[i].getAbsolutePath());
			 }
		 }
		  
	  } 
	
   }
   
    //指定目录下,指定文件后缀的文件信息
    public static void listFilenameByFilenameFilter(FilenameFilter filter,String dirName){
    	 if(!dirName.endsWith(File.separator)){
       	  dirName = dirName + File.separator;
       	  System.out.println(dirName);
         }
         File dirFile = new File(dirName);
   	     if(!dirFile.exists()||!dirFile.isDirectory()){
   		  System.out.println("找不到目录"+dirName);
   	     }
   	  File[] files = dirFile.listFiles(filter);
	  if(files.length > 0){
		 for(int i=0;i<files.length;i++){
			 if(files[i].isFile()){
				 System.out.println(files[i].getAbsolutePath()+"是文件");
				 
			 }else if(files[i].isDirectory()){
				 System.out.println(files[i].getAbsolutePath() + "是目录");
				 ListFileUtil.listFilenameByFilenameFilter(filter,files[i].getAbsolutePath());
			 }
		 }
		  
	  } 
    	
   }
	
    //文件后缀名过滤器,过滤文件后缀名
    //内部类作为该类的成员变量
    static class MyFilenameFilter implements FilenameFilter{
         private String suffix = "";
         public MyFilenameFilter(String suffix){
        	 this.suffix = suffix;
         }
         public boolean accept(File dir, String name) {
		    if(new File(dir,name).isFile()){
		    	return name.endsWith(suffix);
		    }else{
		    	return true;
		    }
	    	 
			 
		}
    	
    }
    
    //测试方法
    public static void main(String[] args) {
   	    String dir = "D:/filetest";
        ListFileUtil.listAllFiles(dir);
        System.out.println();
        System.out.println("经过过滤以后的内容");
        FilenameFilter ff = new ListFileUtil.MyFilenameFilter(".docx");
        ListFileUtil.listFilenameByFilenameFilter(ff,dir);
  	
    }
}


以上功能封装可用于javaSwing 查询文件系统,jsp等对文件的操作

你可能感兴趣的:(java File)