如何使用 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP