Return to Snippet

Revision: 65679
at January 10, 2014 13:12 by c0deslayer


Initial Code
System.out.println("Please enter the filename: ");
    Scanner input = new Scanner(System.in);
    
    String fileName = input.nextLine();
    
     FileReader fReader;
        try {
            fReader = new FileReader(fileName);
            BufferedReader reader = new BufferedReader(fReader);
            String cursor; // 
            String content = "";
            int lines = 0;
            int words = 0;
            int chars = 0;
            while((cursor = reader.readLine()) != null){
                // count lines
                lines += 1;
                content += cursor;
                
                // count words
                String []_words = cursor.split(" ");
                for( String w : _words)
                {
                  words++;        
                }
                
            }
            chars = content.length();
            
            System.out.println("File " + fileName + " has ");
            System.out.println(chars + " Characters,");
            System.out.println(words + " words and " + lines + " lines.");
            
            
        } catch (FileNotFoundException ex) {
           // Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("File not found!");
        } catch (IOException ex) {
            //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
             System.out.println("An error has occured: " + ex.getMessage());
        }

Initial URL

                                

Initial Description
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 ***

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

Initial Tags

                                

Initial Language
Java