使用 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 日

546 人查看

开启你的 职业

通过完成课程获得认证

开始
广告
© . All rights reserved.