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