如何使用 Java 统计文本文件中字符的数量(包括空格)?
统计文件中的行数
通过将所需文件对象作为其构造函数的参数传递,例化 FileInputStream 类。
使用 FileInputStream 类的 read() 方法将文件内容读入字节数组。
通过将获得的字节数组作为其构造函数的参数来实例化一个 String 类。
最后,获取字符串的长度。
示例
import java.io.File;
import java.io.FileInputStream;
public class NumberOfCharacters {
public static void main(String args[]) throws Exception{
File file = new File("data");
FileInputStream fis = new FileInputStream(file);
byte[] byteArray = new byte[(int)file.length()];
fis.read(byteArray);
String data = new String(byteArray);
System.out.println("Number of characters in the String: "+data.length());
}
}
数据

输出
Number of characters in the String: 3
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP