Dear Friends
We discussed in a lecture about Formatter and Scanner. This is just an implementation of that
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class FileHandling {
public int characters=0, words=0, lines=0;
//this method demonstrates how to read from a file
//it also counts the number of lines, words in a line and characters in each word
public void readAFile(String filename) throws IOException {
FileInputStream filestream = new FileInputStream(filename);
Scanner read = new Scanner(filestream);
while (read.hasNextLine()) {
String nextline = read.nextLine();
++lines;
StringTokenizer wordsInLine = new StringTokenizer(nextline);
while (wordsInLine.hasMoreTokens()) {
String nextword = wordsInLine.nextToken();
++words;
characters+=nextword.length();
}
}
System.out.println("Number of lines : " + lines);
System.out.println("Number of words : " + words);
System.out.println("Number of characters: " + characters);
}
public static void main(String[] args) {
try {
FileHandling fl = new FileHandling();
fl.readAFile("FileHandling.java");
} catch (IOException e) {
e.printStackTrace();
}
}
}
0 comments:
Post a Comment