如何用 Java 在文字檔案中計算字元數量(包括空格)?
計算檔案中行數
透過將所需檔案物件作為引數傳遞給建構函式來例項化 FileInputStream 類。
使用 FileInputStream 類的 read() 方法,將檔案內容讀入到位元組陣列中。
將獲得的位元組陣列作為引數,例項化一個字串類,即其建構函式。
最後,找出字串的長度。
示例
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());
}
}
data

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