In: Computer Science
Java
Write a method that reads a text file and prints out the number of words at the end of each line
// Words.txt file contents
Hello, my name
is Michael
Jackson. Welcome to
java programming
world
//Java code starts here
import java.io.BufferedReader; //imports required for file
reading
import java.io.FileReader;
public class Main
{
//Method to print no. of words in every line
//Pass the filename as argument
public static void count_words(String filename) throws
Exception
{String line; //String to store line
int count = 0; //Counter
//Opens a file in read mode
FileReader file = new FileReader(filename);
BufferedReader br = new BufferedReader(file);
//Gets each line till end of file is reached
while((line = br.readLine()) != null) {
//Let us print the line first
System.out.print(line+" ");
//Splits each line into words and store in words array
String words[] = line.split(" ");
//Print length each words[] i.e the number of words
System.out.println(words.length);
}
br.close(); //Close the reader
}
public static void main(String[] args) throws Exception {
count_words("Words.txt");
}
}