如何使用 Java 统计文本文件中的行数?


要统计文件中的行数

  • 通过向其构造函数传递所需文件对象的 FileInputStreamnbsp;类实例化。
  • 使用FileInputStreamnbsp;类的 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

更新于:20-Feb-2020

2 千 + 浏览量

开启您的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.