如何使用 Java 统计文本文件中的单词数?
读取文本文件中的单词数
- 通过将所需文件(对象)作为参数传递给它的构造函数,创建一个FileInputStream对象。
- 使用read()方法将文件的内容读入一个字节数组。
- 将字节数组传递给它的构造函数,实例化一个 String 类。
- 使用split()方法将字符串中的单词读入一个数组。
- 创建一个整型变量,初始化为 0,在字符串数组的 for 循环中,对每个元素增加计数。
示例
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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP