如何使用 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

更新于: 20-Feb-2020

2K+ 浏览

开启你的职业生涯

完成课程,获得认证

开始吧
广告
© . All rights reserved.