如何用 Java 在文本文件中计算字符数量(包括空格)?
计算文件中行数
通过将所需文件对象作为参数传递给构造函数来实例化 FileInputStream 类。
使用 FileInputStream 类的 read() 方法,将文件内容读入到字节数组中。
将获得的字节数组作为参数,实例化一个字符串类,即其构造函数。
最后,找出字符串的长度。
示例
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());
}
}
data

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