统计 某目录下 文件中的 字符

本文介绍了一个使用Java编写的工具类,它可以统计指定目录下所有文件的行数、空格数和数字个数。通过遍历目录中的每一个文件,并逐行读取文件内容进行统计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

统计给定目录下,所有文件中的 行数、空格数、数字个数:

 

package test;

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

public class FileStatic {
	public static void main(String[] args) {
		String path = "E:/file/myfile/msn/";
		folderStatic(path);
	}

	/**
	 * 统计 某个目录下 每个文件的 行数、空格数、数字 个数,
	 * @param folderPath
	 */
	public static void folderStatic(String folderPath) {
		try {
			File folder = new File(folderPath);
			System.out.println("folder [" + folderPath + "] exists? " + folder.exists());
			File[] fList = folder.listFiles();
			System.out.println("contains " + fList.length + " files");

			for (int i = 0; i < fList.length; i++) {
				int lineCount = 0, spaceCount = 0, numberCount = 0;
				File _file = fList[i];
				BufferedReader br = new BufferedReader(new FileReader(_file), 300);
				String line = null;
				while ((line = br.readLine()) != null) {
					lineCount++;
					for (int j = 0; j < line.length(); j++) {
						char _c = line.charAt(j);
						if (_c == ' ') { // 判断空格
							spaceCount++;
						} else if (_c > '0' && _c < '9') { // 判断 数字
							numberCount++;
						}
					}
				}
				System.out.println("[" + _file.getName() + "]:\tline:" + lineCount + "\twhitespace:" + spaceCount + "\tnumber:" + numberCount);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值