使用Java计算文本文件中的段落数
我们可以通过读取字符串中的段落来读取文件中的段落,然后根据“\r\n”模式进行分割。请参阅下面的示例-
示例
在类路径中请看以下文本文件。
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
测试器
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\n\r\n");
return paragraphs.length;
}
}这将产生以下结果-
输出结果
No. of paragraphs in file: 5
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西