Java Program to Count the Number of Lines, Words, Characters, and Paragraphs in a Text File
Counting the number of characters is essential because almost all the text boxes that rely on user input have certain limitations on the number of characters inserted. For example, the character limit on a Facebook post is 63206 characters. Whereas for a tweet on Twitter, the character limit is 140 characters, and the character limit is 80 per post for Snapchat.
Determining character limits become crucial when the tweet and Facebook post updates are being done through APIs.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In-built Functions Used
1. File(String pathname):
This function is present under the java.io.File package. It creates a new File instance by converting the given pathname string into an abstract pathname.
public File(String pathname)
pathname - A pathname string
2. FileInputStream(File file) :
This function is present under the java.io.FileInputStream package. It creates a FileInputStream by opening a connection to an actual file named by the File object file in the file system.
public FileInputStream(File file) throws FileNotFoundException
file - the file to be opened for reading.
- FileNotFoundException – if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.
- SecurityException – if a security manager exists and its checkRead method denies read access to the file.
3. InputStreamReader(InputStream in):
This function is present under the java.io.InputStreamReader package. It creates an InputStreamReader that uses the default charset.
public InputStreamReader(InputStream in)
in - An InputStream
4. BufferedReader(Reader in):
This function is present under the java.io.BufferedReader package. It creates a buffering character-input stream that uses a default-sized input buffer.
public BufferedReader(Reader in)
in - A Reader
The TextReader.txt file contains the following data –
Hello Geeks. My name is Nishkarsh Gandhi. GeeksforGeeks is a Computer Science portal for geeks.
Note: This program would not run on online compilers. Please make a txt file on your system and give its path to run this program on your system.
This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect or you want to share more information about the topic discussed above.