In any Java technical Interview it is a common question asked by the interviewer, how to count number of lines characters and words in a file Java. Here is the example.

count number of lines characters and words in a file

[sourcecode language=”java”]

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
 *
 * @author chandrashekhar
 */
public class CountDemo {

    final String FILE_PATH = "/home/chandrashekhar/Desktop/FileOperations.txt";

    public static void main(String[] args) {
        try {
            CountDemo cd = new CountDemo();
            System.out.println("lines: " + cd.getLineCount());
            System.out.println("words: " + cd.getWordCount());
            System.out.println("characters: " + cd.getCharacterCount());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int getLineCount() {
        LineNumberReader reader = null;
        int lines_count = 0;
        try {
            reader = new LineNumberReader(new InputStreamReader(new FileInputStream(new File(FILE_PATH))));
            while (reader.readLine() != null) {
                lines_count = reader.getLineNumber();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lines_count;
    }

    public int getWordCount() {
        int word_count = 0;
        LineNumberReader reader = null;
        String line = "";
        try {
            reader = new LineNumberReader(new InputStreamReader(new FileInputStream(new File(FILE_PATH))));
            while ((line = reader.readLine()) != null) {
                word_count += line.split(" ").length;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return word_count;
    }

    public int getCharacterCount() {
        int character_count = 0;
        LineNumberReader reader = null;
        String line = "";
        try {
            reader = new LineNumberReader(new InputStreamReader(new FileInputStream(new File(FILE_PATH))));
            while ((line = reader.readLine()) != null) {
                character_count += line.toCharArray().length;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return character_count;
    }
}

[/sourcecode]

 

To run the above example, you have to make sure that create a file on your desktop and give a name as “FileOperations.txt”.  And assign the complete path to FILE_PATH.

Output:

lines: 9
words: 8
characters: 33

You may also Like :   Writing data to a file in Java