如何使用 Java 統計文字檔案中字元的數量(包括空格)?
統計檔案中的行數
透過將所需檔案物件作為其建構函式的引數傳遞,例化 FileInputStream 類。
使用 FileInputStream 類的 read() 方法將檔案內容讀入位元組陣列。
透過將獲得的位元組陣列作為其建構函式的引數來例項化一個 String 類。
最後,獲取字串的長度。
示例
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);
System.out.println("Number of characters in the String: "+data.length());
}
}
資料

輸出
Number of characters in the String: 3
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP