Java中的I/O流以及File类实现读取文件的行数、单词量和字符数

本文介绍了一种使用Java进行文件分析的方法,包括读取文件的行数、统计单词数量、计算字符总数以及查找特定字母的出现次数。

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

要求:给定一份txt文件,读取文件的行数,单词数,字符数(包括空格和标点符号)以及查阅某一单词在文件中出现的次数。

  1. 读取文件的行数
public static void ReadFile() throws FileNotFoundException,IOException{
		//读取文件的行数
		int count_line=0;
		File file = new File(filepath);
		FileInputStream filelines = new FileInputStream(file);
		Scanner input = new Scanner(filelines);
		while(input.hasNextLine()){
		input.nextLine();
		count_line++;
		}
		System.out.println("该文本文件的行数为:" + count_line);
		input.close();
	}
  1. 统计文件的单词数量
public static void WordNumber() throws IOException {
		//读取文件的单词数
		FileReader file = new FileReader(filepath);
		int x = file.read();
		int wordnumber = 0;
		while(x != -1) {
			if( (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z') ) {
				wordnumber++;
				x = file.read();
				while((x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z')) {
					x = file.read();
				}
			}
			else
				x = file.read();
		}
		file.close();
		System.out.println("该文本中的单词个数是:" + wordnumber);
	}
  1. 统计文件的字符数
public static void CharacterNumebr() throws IOException{
		FileReader file = new FileReader(fiepath);
		BufferedReader in = new BufferedReader(file);
		String str = null;
		int character = 0;
		while((str = in.readLine()) != null) {
			character += str.length();
		}
		in.close();
		System.out.println("该文件的总字符数为:" + character);	
	}
  1. 统计给定字母在文本中出现的次数
public static void LetteNumber() throws IOException{
		FileReader file = new FileReader(filepath);
		BufferedReader in = new BufferedReader(file);
		StringBuffer strb = new StringBuffer();
		Scanner input = new Scanner(System.in);
		System.out.println("请输入需要查询的字母:");
		String key = input.next();
		char s = key.charAt(0);
		if((s >= 'A' && s <= 'Z') || (s >= 'a' && s <= 'z')) {
			while(true) {
				String line = in.readLine();
				if(line == null) 
					break;
				strb.append(line);
			}
			String result = strb.toString();
			int count = 0;
			int index = 0;
			while(true) {
				index = result.indexOf(key,index + 1);
				if(index > 0) 
					count ++;
				else 
					break;
			}
			input.close();
			in.close();
			System.out.println(key + "一共出现了" + count + "次");
		}
		else 
			System.out.println("您的输入为特殊字符,请重新输入!");
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值