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

Including Spaces

輸出

Number of characters in the String: 3

更新於: 30-Jul-2019

611 次瀏覽

事業升遷

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.