View Single Post
Join Date: Jul 2008
Posts: 28
Reputation: newtechie is an unknown quantity at this point 
Solved Threads: 0
newtechie newtechie is offline Offline
Light Poster

Re: word/line/character count in files

 
0
  #5
Sep 2nd, 2008
i modified the count word part and got the desired output
  1. /*
  2.  pgm to count the characters in a file,no. of lines in a file and no. of words
  3.  */
  4. import java.io.*;
  5. public class countCharacters
  6. {
  7. public void Lines()throws IOException
  8. {
  9. File f = new File("in.dat");
  10. FileReader fr = new FileReader(f);
  11. BufferedReader br = new BufferedReader(fr);
  12. String str = br.readLine();
  13.  
  14. LineNumberReader ln = new LineNumberReader(br);
  15. int count = 0;
  16. while (ln.readLine()!=null)
  17. {
  18. count++;
  19. }
  20.  
  21. System.out.println("no. of lines in the file = " + count);
  22.  
  23. }
  24. public void Words()throws IOException
  25. // count no. of words.
  26. {
  27. File f = new File("in.dat");
  28. FileReader fr = new FileReader(f);
  29. BufferedReader br = new BufferedReader(fr);
  30. StreamTokenizer stz = new StreamTokenizer(br);
  31. int index = 0;
  32. int numWords =0;
  33.  
  34. while(index !=StreamTokenizer.TT_EOF )
  35. {
  36. index =stz.nextToken();
  37. numWords++;
  38. }
  39.  
  40. System.out.println("no. of words in file = " + numWords);
  41. }
  42. public void Charact()throws IOException
  43. // counting characters
  44. {
  45. File f = new File("in.dat");
  46. FileReader fr = new FileReader(f);
  47. BufferedReader br = new BufferedReader(fr);
  48. long numChar = f.length();
  49. int countChar =0;
  50. while(countChar<numChar)
  51. {
  52. countChar++;
  53. }
  54. System.out.println("no. of characters in the file =" + countChar);
  55. // return countChar;
  56.  
  57. }
  58. public static void main(String args[])throws IOException
  59. {
  60. countCharacters ob1 = new countCharacters();
  61. ob1.Charact();
  62. ob1.Words();
  63. ob1.Lines();
  64.  
  65. }
  66. }
Last edited by cscgal; Sep 2nd, 2008 at 10:49 pm. Reason: Fixed code tags
Reply With Quote