如何使用 Java 统计文本文件中行数?
统计文件中行数
- 通过将所需文件的对象作为其构造函数的参数传入,实例化**FileInputStream** 类。
- 使用**FileInputStream** 类的 **read()** 方法,将文件内容读入字节数组。
- 通过将获得的字节数组作为其构造函数的参数传入,实例化一个 String 类。
- 现在,使用**split()** 方法,通过将换行的正则表达式作为该方法的参数传入,将上述字符串拆分为一个字符串数组。
- 现在,获得数组长度。
示例
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);
String[] stringArray = data.split("\r
");
System.out.println("Number of lines in the file are ::"+stringArray.length);
}
}data

输出
Number of lines in the file are ::3
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP