利用 Java 計算文字檔案中的段落數\n


我們可以透過將檔案讀入到一個字串中,然後基於“\r
”模式進行拆分,來讀取檔案中的段落。請參見以下示例 −

示例

考慮類路徑中的以下文字檔案。

test.txt

This is Line 1

This is Line 2
This is Line 3

This is Line 4
This is Line 5

This is Line 6
This is Line 7

This is Line 8
This is Line 9
This is Line 10

Tester.java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Tester {
   public static void main(String args[]) throws IOException {
      FileUtil fileUtil = new FileUtil();
      System.out.println("No. of paragraphs in file: " + fileUtil.getParaCount());
   }
}

class FileUtil {
   private static final String FILE_PATH = "data.txt";
   
   public static int getParaCount() throws IOException {
      File file = new File(FILE_PATH);
      FileInputStream fileStream = new FileInputStream(file);
      byte[] byteArray = new byte[(int)file.length()];
      fileStream.read(byteArray);
      String data = new String(byteArray);

      String[] paragraphs = data.toString().split("\r
\r
");       return paragraphs.length;    } }

它會產生以下結果 −

輸出

No. of paragraphs in file: 5

更新於:2020 年 6 月 19 日

547 次瀏覽

開啟您的職業

透過完成課程獲得認證

馬上開始
廣告