Java文件的字数统计

Java第七章作业

编写一个程序,程序实现对用户指定的文本文件中的英文字符和字符串的个数进行统计的功能,并将结果根据用户选择输出至结果文件或屏幕。

  • 构建统计类,该类实现对I/O的操纵;实现对文本文件中英文字符、字符串的统计;实现对统计结果的输出。
  • 构建测试类,该类实现与用户的交互,向用户提示操作信息,并接收用户的操作请求。
import java.io.*;
import java.util.Scanner;


public class FileAlphaCounter {
	public static void main(String[] args) {
		int c = 0;
		Scanner sc = new Scanner(System.in);
		String address = sc.nextLine();
		String name = sc.nextLine(); 
		FileInputStream in= null;
		BufferedWriter bw = null;
		try {
			in = new FileInputStream(address+name);
			bw = new BufferedWriter(new FileWriter(address+"Countof"+ name +".txt"));
		}
		catch(FileNotFoundException e){
			System.out.println("未找到该文件");
		}
		catch(IOException error) {
			System.out.println("文件创建错误");
		}
		try {
			int num_of_num = 0;
			int num_of_chara = 0;
			while((c = in.read()) != -1) {
				if(c >= '0' && c < '9') {
					num_of_num++;
				}
				else if(c >= 'A' && c <='Z'|c >= 'a' && c <='z' ) {
					num_of_chara++;
				}
			}
			System.out.println("Character:" + num_of_chara);
			System.out.println("Cumber:" + num_of_num + "\nDone!");
			String result = "Character:" + num_of_chara;
			String info = "The result of "+ address + name + " is : ";
			bw.write(info);
			bw.newLine();
			bw.write(result);
			bw.newLine();
			result = "Number:" + num_of_num;
			bw.write(result);
			bw.flush();
		}
		catch(IOException error){
			System.out.println("输出错误");
		}
		finally {
			sc.close();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值