count characters, words and lines in file

后端 未结 8 1752
离开以前
离开以前 2020-12-18 16:47

This should count number of lines, words and characters into file.

But it doesn\'t work. From output it shows only 0.

Code:

8条回答
  •  Happy的楠姐
    2020-12-18 17:33

    Different approach. Using strings to find line,word and character counts:

    public static void main(String[] args) throws IOException {
            //counters
            int charsCount = 0;
            int wordsCount = 0;
            int linesCount = 0;
    
            Scanner in = null;
            File selectedFile = null;
            JFileChooser chooser = new JFileChooser();
            // choose file 
            if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                selectedFile = chooser.getSelectedFile();
                in = new Scanner(selectedFile);
            }
    
            while (in.hasNext()) {
                String tmpStr = in.nextLine();
                if (!tmpStr.equalsIgnoreCase("")) {
                    String replaceAll = tmpStr.replaceAll("\\s+", "");
                    charsCount += replaceAll.length();
                    wordsCount += tmpStr.split(" ").length;
                }
                ++linesCount;
            }
    
            //display the count of characters, words, and lines
            System.out.println("# of chars: " + charsCount);
            System.out.println("# of words: " + wordsCount);
            System.out.println("# of lines: " + linesCount);
    
            in.close();
        }
    


    Note:
    For other encoding styles use new Scanner(new File(selectedFile), "###"); in place of new Scanner(selectedFile);.

    ### is the Character set to needed. Refer this and wiki

提交回复
热议问题