获取指定目录及子目录下所有txt文件的个数,并将这些txt文件复制到自定义任意目录

注意:1.打印流pw关闭前需进行判空,否则会报空指针异常

          2.需用count接收递归调用时返回的count值,否则遍历子目录后返回的还是父目录的count值

public class TxtDemo {
	public static void main(String[] args) {
		 System.out.println("txt文件的个数为 :" + countAndCopy(new File("e:\\demo"), new File("e:\\demo1\\b"),0));
	}
	
	/*
	 * 定义方法,获取指定目录下txt文件的个数
	 * 并将这些txt文件复制到自定义目录
	 */
	public static int countAndCopy(File src,File dest,int count) {
		BufferedReader bfr = null;
		PrintWriter pw = null;
		try {
			File[] fileArr = src.listFiles();
			for(File f : fileArr) {
				if(f.isDirectory()) {
					//应设置count变量接收目录里面的count值并进行返回,否则遍历完子目录,返回父目录时,count值依旧是父目录里的count值
					count = countAndCopy(f,dest,count);
				}else {
					if(f.getName().endsWith(".txt")) {
						bfr = new BufferedReader(new FileReader(f));
						pw = new PrintWriter(new FileWriter(dest.getAbsolutePath() + "\\" + f.getName()),true);
						++count;
						String line = null;
						while((line = bfr.readLine()) != null) {
							pw.println(line);
						}
					}
				}
			}
			//注意应对打印流进行判空,否则遍历一个没有.txt文件的目录时会报NullPointerException
			if(pw != null)
				pw.close();
		}catch(IOException ex) {
			System.out.println(ex);
			throw new RuntimeException("读写文件失败");
		}finally {
			try {
				if(bfr != null)
					bfr.close();
			}catch(IOException ex) {
				throw new RuntimeException("释放文件失败");
			}
		}
		return count;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值