如何使用Java计算文本文件中的单词数?
读取文本文件中的单词数
通过将所需的文件(对象)作为参数传递给其构造函数来创建FileInputStream 对象。
使用read()方法将文件的内容读取到字节数组中。
通过将字节数组传递给其构造函数来使String类满意。
使用 split() 方法将String的单词读取到数组中。
创建一个整数变量,将其初始化为0,对于字符串数组的每个元素,intfor循环将增加计数。
示例
import java.io.File;
import java.io.FileInputStream;
public class Sample {
public static void main(String args[]) throws Exception{
int count =0;
File file = new File("data");
FileInputStream fis = new FileInputStream(file);
byte[] bytesArray = new byte[(int)file.length()];
fis.read(bytesArray);
String s = new String(bytesArray);
String [] data = s.split(" ");
for (int i=0; i<data.length; i++) {
count++;
}
System.out.println("Number of characters in the given file are " +count);
}
}输出结果
Number of characters in the given String are 4
热门推荐
10 给弟弟的祝福语简短
11 领证祝福语高级文案简短
12 新婚简短祝福语微信
13 亲人提升的祝福语简短
14 感恩卡片的祝福语 简短
15 赞美祝福语大全简短的
16 毕业祝福语小长句简短
17 简短宝贝祝福语大全集
18 花篮考学祝福语大全简短