使用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP