Counting number of whitespaces in text file using java

Java Programming Java8Object Oriented Programming

Here is an example of counting white spaces in text file using java,hope this helps you.

Example


import java.io.*;
public class CountWhiteSpace {
   public static void main(String[] args) throws IOException {
      File file = new File("C:\\Users\\myjava\\count.txt"); //Creates a new File instance by       converting the given pathname string into an abstract pathname
      FileInputStream fn = new FileInputStream(file); //Instantiate the FileInputStream class by          passing an object of the required file as parameter to its constructor.
      InputStreamReader input = new InputStreamReader(fn); //Creates an InputStreamReader that uses          the default charset.
      BufferedReader reader = new BufferedReader(input); //Creates a buffering character-input stream       that uses a default-sized input buffer.
      String sentence;
      // Initializing counters
      int countWord = 0,whitespaceCount = 0;
      if((sentence= reader.readLine()) != null) {
         String[] wordlist = sentence.split("\\s+"); // \\s+ is the space delimiter in java
         countWord += wordlist.length;
         whitespaceCount += countWord -1;
      }
      System.out.println(" Number of whitespaces = " + whitespaceCount);
   }
}

count.txt

Whitespaces

Output

Command Prompt

raja
Published on 01-Oct-2018 11:58:38
Advertisements