黑马程序员技术交流社区

标题: IO流综合练习02 [打印本页]

作者: _J2EE_LiXiZhen    时间: 2017-11-19 22:54
标题: IO流综合练习02
在d盘目录下有一个加密文件a.txt(文件里只有英文和数字),密码是“heima”
当密码输入正确时才能读取文件里的数据。现要求用代码来模拟读取文件的过程,并统计文件里各个字母出现的次数,并把统计结果按照如下格式输出到d盘的count.txt中。
a:2个
b:3个
c:4个

[Java] 纯文本查看 复制代码
public class Test02 {
        public static void main(String[] args) throws IOException {
                Scanner sc = new Scanner(System.in);
                HashMap<Character, Integer> map = new HashMap<Character, Integer>();
                System.out.println("请输入密码:");
                String psw = sc.nextLine();
                // 判断密码是否正确
                if ("heima".equals(psw)) {
                        // 字符数量,初始为1
                        int value = 1;
                        // 创建字节输入流对象
                        FileInputStream fis = new FileInputStream("a.txt");
                        // 往map里读取数据
                        int len;
                        while ((len = fis.read()) != -1) {
                                char key = (char) len;
                                // 判断有效字符a-z,A-Z
                                if (key >= 'a' && key <= 'z' || key >= 'A' && key <= 'Z') {
                                        // 判断map里有没有该字符
                                        if (map.get(key) == null) {
                                                // 如果没有就添加,数量初始为1
                                                map.put(key, value);
                                        } else {
                                                // 如果有数量就加以
                                                map.put(key, map.get(key) + 1);
                                        }
                                }
                        }
                        // 关闭流
                        fis.close();
                        // 遍历集合map
                        for (char key : map.keySet()) {
                                System.out.println(key + ": " + map.get(key) + "个");
                        }
                } else {
                        System.out.println("密码错误,读取文件失败");
                }
        }
}





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2