![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Counting number of paragraphs in text file using java\n
We can read paragraphs in a file by reading it in a string and then spilting based on "\r
" pattern. See the example below −
Example
Consider the following text file in the classpath.
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; } }
This will produce the following result −
Output
No. of paragraphs in file: 5
Advertisements