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