we will implement the unix program wc in java. The program wc counts the number
ID: 3751036 • Letter: W
Question
we will implement the unix program wc in java. The program wc counts the number of words, lines, and characters in a file. The unix wc command can take input from a file or from standard input, for this exercise, our version will not accept standard input. If the user does give a file parameter, the program will print out instructions for use.
Note that <filename> can be a single file, or a file specification such as *.c. If multiple files are specified you must print the statistics for all of the specified files. If there is any doubt about the behavior, refer to how the command functions on any modern linux system. In other words, unless otherwise specified, the behavior of your code must match as closely as possible to the linux variant.
Explanation / Answer
import java.io.*;
class FileDemo
{
public static void main(String args[])
{
try
{
int lines=0,chars=0,words=0;
int code=0;
FileInputStream fis = new FileInputStream("sample.txt");
while(fis.available()!=0)
{
code = fis.read();
if(code!=10)
chars++;
if(code==32)
words++;
if(code==13)
{
lines++;
words++;
}
}
System.out.println("No.of characters = "+chars);
System.out.println("No.of words = "+(words+1));
System.out.println("No.of lines = "+(lines+1));
fis.close();
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOException i)
{
System.out.println("Cannot read file...");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.