Thursday, 12 April 2018

Corejava-Slip18

Slip18: Write a java program that displays the number of characters,lines & words from a file.

import java.io.*;
class Rev
{
public static void main(String args[])throws Exception
{
int ccnt=0,lcnt=1,wcnt=0,c;
FileInputStream fin=new FileInputStream(args[0]);
while((c=fin.read())!=-1)
{
ccnt++;
if(c==32||c==13)
wcnt++;
if(c==13)
cnt++;
}
System.out.println("Number of Characters are:"+ccnt);
System.out.println("Number of Words are:"+wcnt);
System.out.println("Number of Lines:"+lcnt);
}
}


Another way

import java.io.*;
class Slip18
{
public static void main(String a[]) throws Exception
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter source file name ");
String f1=br.readLine();
FileReader fr = new FileReader(f1);
int ch ;
int wc= 0,line=0, cc=0;
while((ch=fr.read())!= -1)
{ char c = (char)ch;
cc++;
if(c=='\n')
{ line++;
wc++;
}
else if(c==' ' || c=='\n')
wc++;
}
System.out.println("Line count = "+line+"\n Character
count = "+cc+"\n word count = "+wc);
fr.close();
}
}