How to count the number of characters (including spaces) in a text file using Java?


To count the number of lines in a file

  • Instantiate the FileInputStream class by passing an object of the required file as parameter to its constructor.

  • Read the contents of the file to a byte array using the read() method of FileInputStream class.

  • Instantiate a String class by passing the byte array obtained, as a parameter its constructor.

  • Finally, find the length of the string.

Example

import java.io.File;
import java.io.FileInputStream;

public class NumberOfCharacters {
public static void main(String args[]) throws Exception{
   File file = new File("data");
      FileInputStream fis = new FileInputStream(file);
      byte[] byteArray = new byte[(int)file.length()];
      
      fis.read(byteArray);
      String data = new String(byteArray);
      System.out.println("Number of characters in the String: "+data.length());
   }
}

data

Including Spaces

Output

Number of characters in the String: 3

Updated on: 30-Jul-2019

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements