集册 Java实例教程 使用BufferedReader计数字母

使用BufferedReader计数字母

欢马劈雪     最近更新时间:2020-01-02 10:19:05

492
用BufferedReader计算字母

import java.io.*;

import java.nio.file.*;
/*from N o  w  J a v a . c o m - 时  代  Java*/

public class CountLetter {

    private char lookFor;

    private Path file;


    CountLetter(char lookFor, Path file) {

        this.lookFor = lookFor;

        this.file = file;

    }


    public int count() throws IOException {

        int count = 0;

        try (InputStream in = Files.newInputStream(file);

                BufferedReader reader = new BufferedReader(

                        new InputStreamReader(in))) {

            String line = null;

            while ((line = reader.readLine()) != null) {

                for (int i = 0; i < line.length(); i++) {

                    if (lookFor == line.charAt(i)) {

                        count++;
                        /**
                         * 时 代 J a v a 公 众 号 提 供 
                        **/

                    }

                }

            }

        } catch (IOException x) {

            System.err.println(x);

        }

        return count;

    }


    static void usage() {

        System.out.println("usage: java CountLetter <letter>");

        System.exit(-1);

    }


    public static void main(String[] args) throws IOException {


        if (args.length != 1 || args[0].length() != 1)

            usage();


        char lookFor = args[0].charAt(0);

        Path file = Paths.get("xanadu.txt");

        int count = new CountLetter(lookFor, file).count();

        System.out.format("File '%s' has %d instances of letter '%c'.%n",

                file, count, lookFor);

    }

}


展开阅读全文