Program
To count the number of lines, words and characters in a file.
Algorithm
Step 1: Start
Step 2: Initialize variables words, lines chars to 0
Step 3: Call count(InputStreamReader)
Step 4: Print lines, words, chars
Step 5: Stop
Function public static void count(InputStreamReader isr)
Step 1: Start
Step 2: Initialise FileInputStream pointer infile
Step 3: Read fname
Step 4: Initialise FileOutputStream pointer outfile and open file in output mode
Step 5: Read input and write it to file using outfile
Step 6: Close file
Step 7: Open file using infile in input mode
Step 8: Repeat steps 9-17 reading each character c until end of file
Step 9: char=char+1
Step 10: if(c==’\n’) go to step 11 else to18
Step 11: lines=lines+1
Step 12: index=ws.indexOf(c)
Step 13: if(index==-1) go to 14 else to 17
Step 14: if(set) then go to 13 else to 16
Step 15: words=words+1
Step 16: set=false go to 18
Step 17: set=true
Step 18: l=lines+words
Step 19: chars=chars-l
Step 20: Exit.
Program
import java.io.*; import java.util.StringTokenizer; class ProcessFile { long words,lines,chars; File fn; FileInputStream in; DataInputStream ins; ProcessFile(String fname) { words=lines=chars=0; fn= new File(fname); } void Process() { int ch; String s,tok=" \t\n",temp; StringTokenizer st; try { in=new FileInputStream(fn); ins=new DataInputStream(in); chars=fn.length(); while(ins.available()!=0) { s=ins.readLine(); lines++; st=new StringTokenizer(s,tok); words=words+st.countTokens(); } } catch (Exception e) { System.out.println(e); System.exit(0); } } void PrintDetails() { if(fn.exists()) { System.out.println("The " + fn.getAbsolutePath() + " contains."); System.out.println("Lines = " + lines); System.out.println("Words = " + words); System.out.println("Characters = " + chars); } else { System.out.println("The file " + fn.getAbsolutePath() + " does not exit."); } } } public class MyWord { public static void main(String args[]) { String fname; DataInputStream in=new DataInputStream(System.in); System.out.println("Enter the filename : "); try { fname=in.readLine(); ProcessFile pf=new ProcessFile(fname); pf.Process(); pf.PrintDetails(); } catch(Exception e) { System.out.println(e); } } } |
Output
Enter the filename :
c:\a.txt
The c:\a.txt contains.
Lines = 4
Words = 10
Characters = 30
Leave a Reply