Posted By

c0deslayer on 01/10/14


Tagged


Versions (?)

Java Program: Count characters, words and lines in a text file


 / Published in: Java
 

  1. Write a program that counts the number of characters including words and lines in a file. The program prompts the user for inputting the filename. Sample output as follows:

Please enter the filename: narrative.txt

File Sample.txt has

1732 characters,

204 words and 70 lines.

*** by c0deslayer ***

  1. System.out.println("Please enter the filename: ");
  2. Scanner input = new Scanner(System.in);
  3.  
  4. String fileName = input.nextLine();
  5.  
  6. FileReader fReader;
  7. try {
  8. fReader = new FileReader(fileName);
  9. BufferedReader reader = new BufferedReader(fReader);
  10. String cursor; //
  11. String content = "";
  12. int lines = 0;
  13. int words = 0;
  14. int chars = 0;
  15. while((cursor = reader.readLine()) != null){
  16. // count lines
  17. lines += 1;
  18. content += cursor;
  19.  
  20. // count words
  21. String []_words = cursor.split(" ");
  22. for( String w : _words)
  23. {
  24. words++;
  25. }
  26.  
  27. }
  28. chars = content.length();
  29.  
  30. System.out.println("File " + fileName + " has ");
  31. System.out.println(chars + " Characters,");
  32. System.out.println(words + " words and " + lines + " lines.");
  33.  
  34.  
  35. } catch (FileNotFoundException ex) {
  36. // Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
  37. System.out.println("File not found!");
  38. } catch (IOException ex) {
  39. //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
  40. System.out.println("An error has occured: " + ex.getMessage());
  41. }

Report this snippet  

You need to login to post a comment.