如何使用Java計算文字檔案中的單詞數?


讀取文字檔案中的單詞數

  • 建立FileInputStream 物件,方法是將所需檔案(物件)作為 引數傳遞給其建構函式。
  • 使用read()方法將檔案的內容讀入位元組陣列中。
  •  透過將位元組陣列傳遞給其建構函式來例項化一個 String 類。
  • 使用 split() 方法將 String 中的單詞讀入陣列。
  • 建立一個整數變數,用 0 初始化,在 for 迴圈中為 String 陣列的每個元素增加計數。

示例

import java.io.File;
import java.io.FileInputStream;
public class Sample {
   public static void main(String args[]) throws Exception{

      int count =0;
      File file = new File("data");
      FileInputStream fis = new FileInputStream(file);
      byte[] bytesArray = new byte[(int)file.length()];
      fis.read(bytesArray);
      String s = new String(bytesArray);
      String [] data = s.split(" ");
      for (int i=0; i<data.length; i++) {
         count++;
      }
      System.out.println("Number of characters in the given file are " +count);
   }
}

輸出

Number of characters in the given String are 4


更新於: 20-2-2020

5K+ 檢視

助力你的 職業發展

完成課程獲得認證

入門
廣告
© . All rights reserved.