`
xtuali
  • 浏览: 11971 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

JAVA读取目录下的.txt文件——凤凰网面试

阅读更多

读取目录下的.txt或者.log文件

 

package getFiles;

import java.io.File;
import java.io.FileFilter;

public class FindFiles {
	public static void main(String[] args) {
		printFiles(new File("E:\\DeskTop\\"), new String[]{".txt",".log"});
	}
	
	public static void printFiles(File f, final String[] endString){
		if(!f.isDirectory()){
			System.out.println(f.getAbsolutePath());
			return;
		}
		//文件在读取列表的时候就过滤
		File[] fs = f.listFiles(new FileFilter() {
			public boolean accept(File pathname) {
				return checkReg(pathname, endString);
			}
			
			/**
			 * 新增方法 检查当前文件是否符合要求
			 * @param pathname 当前文件
			 * @param endStrs 文件结尾的字符串
			 * @return
			 */
			private boolean checkReg(File pathname, String[] endStrs){
				boolean isAccept = false;
				for(String endStr : endStrs){
					isAccept = isAccept || pathname.getName().endsWith(endStr);
				}
				return isAccept || pathname.isDirectory();
			}
		});
		for(File tf : fs){
			//递归调用本方法
			printFiles(tf, endString);
		}
	}
	
	
}

 

0
3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics