A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© zhangganxi 中级黑马   /  2016-7-17 10:27  /  322 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package com.Test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/*题目3:在d盘目录下有一个加密文件a.txt(文件里只有英文和数字),
密码是“heima”,当密码输入正确时才能读取文件里的数据。现要求用代码来模拟读取文件的过程,
并统计文件里各个字母出现的次数,并把统计结果按照“a:2个;b:3个;”的格式输出到d盘的count.txt中*/
public class Test3 {
        public static void main(String[] args) throws IOException {
                /*BufferedInputStream bi = new BufferedInputStream(new FileInputStream("D:\\a.txt"));
                BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream("D:\\copy.txt"));
                int b;
                while((b = bi.read())!=-1){
                        bo.write(b^123);
                }
                bi.close();
                bo.close();*/
                Scanner sc = new Scanner(System.in);
                System.out.println("请输入:");
                while(true){
                        String s = sc.nextLine();
                        if (s.equals("黑马")) {
                                method1();
                                break;
                        }else{
                                System.out.println("输入错误,再来一次:");
                        }
                }
        }

        public static void method1() throws FileNotFoundException, IOException {
                BufferedInputStream bi = new BufferedInputStream(new FileInputStream("D:\\copy.txt"));
                StringBuilder sb = new StringBuilder();
                int b;
                while((b=bi.read())!=-1){
                        sb.append((char)(b^123));
                }
                char[] arr = sb.toString().toCharArray();
                Map<Character, Integer> map = new HashMap<>();
                for (int i = 0; i < arr.length; i++) {
                        if (!map.containsKey(arr[i])) {
                                map.put(arr[i],1);
                        }else{
                                map.put(arr[i], map.get(arr[i])+1);
                        }
                }
                BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream("count.txt"));
                for (Character c : map.keySet()) {
                        int i = map.get(c);
                        bo.write((c+":"+i+"个; ").getBytes());
                }
                bo.close();
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马