【Java】题目:读取并分析文件夹

【题目】

输入文件夹地址,读取文件夹所有文件并分析

需求:

  • 判断文件夹是否为空
  • 循环读取文件夹下所有文件夹的所有文件
  • 分析所有文件
package analyze;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;

public class FileOperation {
	private int countbyte = 0;
	private int countBlank = 0;
	private int countTotalLine = 0;
	
	private int totalLine = 0;
	private int blank = 0;
	private int bytes = 0;
	private int files = 0;
	
	private int curlevel;			//层数记录
	
	FileOperation(File dir,int level) throws Exception{
		File[] listfiles = new File[dir.listFiles().length];
		listfiles = dir.listFiles();
		curlevel = level;
		
		System.out.println(new String(new char[curlevel++]).replace("\0", "    ") + "+" + dir.getName());
		count(listfiles);
	}
	
	private void count(File[] listfiles) throws Exception {			//对于文件夹的操作
		for(int i = 0;i < listfiles.length;i++) {
			if(listfiles[i].isFile()) {
				countbyte = 0;
				countBlank = 0;
				countTotalLine = 0;
				
				single(listfiles[i]);
				
				totalLine += countTotalLine;
				blank += countBlank;
				bytes += countbyte;
				files ++;
				//统计单个文件
			}
			else if(listfiles[i].isDirectory()){
				FileOperation fn = new FileOperation(listfiles[i],curlevel);
				totalLine += fn.getTotalLine();
				blank += fn.getBlank();
				bytes += fn.getBytes();
				files += fn.getFiles();
			}
			
		}
		
		
	}
	
	private void single(File file) throws Exception {			//单个文件分析
		Reader reader = new FileReader(file);
		BufferedReader in = new BufferedReader(reader);
		String line = null;
		
		while((line = in.readLine()) != null) {
			line = line.trim();
			if(line.isEmpty()) {
				countBlank++;
			}
			countbyte += line.getBytes().length;
			countTotalLine++;
		}
		in.close();
		System.out.print(new String(new char[curlevel]).replace("\0", "    "));
		System.out.printf("-%-30s Toatal:%6d,Blank:%6d,%10d Bytes\n",file.getName(),countTotalLine,countBlank,countbyte);
		
	}
	
	public int getTotalLine() {
		return totalLine;
	}
	
	public int getBlank() {
		return blank;
	}
	
	public int getBytes() {
		return bytes;
	}
	
	public int getFiles() {
		return files;
	}
}

输出: 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值