从磁盘上读取一个文本文件,分别统计出其中英文字母、空格、数字的个数。

代码:

public static void main(String[] args) {
try(InputStream inputStream = new BufferedInputStream(new FileInputStream("Day25_IO01\\src\\homework\\test.txt"))
) {

//定义统计变量letterCount(字母),spaceCount(空格),numberCount(数字)
int letterCount = 0;
int spaceCount = 0;
int numberCount = 0;

byte[] bytes = new byte[1024];
int read;
while ((read = inputStream.read(bytes)) != -1){
String s = new String(bytes,0,read);
//将获取到的数据转换成字符数组
char[] c = s.toCharArray();
//遍历数组并判断包含情况
for (int i = 0; i < c.length; i++) {
if(Character.isLetter(c[i])){
letterCount++;
}else if(Character.isSpaceChar(c[i])){
spaceCount++;
}else if(Character.isDigit(c[i])){
numberCount++;
}
}
}

//打印统计结果
System.out.println("文件中英文字母个数为:" + letterCount);
System.out.println("文件中空格个数为:" + spaceCount);
System.out.println("文件中数字个数为:" + numberCount);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

猜你喜欢

转载自www.cnblogs.com/bug-baba/p/10540227.html
今日推荐