Java 使用IO流读取txt文件 以及避坑点

一. 编程题
2.1 注解,文件IO和字符串解析操作
已知文件 jdbc.txt
className=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/gp_01
username=root
password=root
要求针对于注解,注解用于在代码中提供 jdbc.txt 文件路径利用 io 读取文件内容将 文件内容读取存储到 HashMap<String, String> 中

private static HashMap<String, String> map1 = new HashMap<String, String>();
    public static void main(String[] args) throws Exception {
        Demo1.tFileInputStream();
    }


    public static void tFileInputStream() throws Exception{
        FileInputStream fileInputStream = new FileInputStream("C:/Users/12997/Documents/WeChat Files/wxid_ckew8ta6dsu622/FileStorage/File/2023-03/周考/jdbc.txt");
        byte[] bytes = new byte[1024*5];
        int len = 0;
        StringBuilder sb = new StringBuilder();
        String str = bytes.toString();
        while ((len = fileInputStream.read(bytes))!=-1){
            sb.append(new String(bytes,0,len));
        }
        fileInputStream.close();
        String s = sb.toString();
        String[] split1 = s.split("\r\n");       //  必须先以换行分割,要不然先以等号的话,会导致,上一行的末尾,和下一行的开头分到同一个数组结点内
                                                //  例如 上一行的末尾  com.mysql.jdbc.Driver    和下一行的开头 username    分到一个数组结点内
                                                //  
        for (String s1 : split1) {
            //System.out.println("s1 = " + s1);
            //String[] split = s1.split("=");
            int index = s1.indexOf("=");
            map1.put(s1.substring(0,index),s1.substring(index + 1));

        }


        //增强for循环
        map1.forEach((key, value) -> {
            System.out.println(key);
            System.out.println(value);
        });
        //迭代器有点low
//        Set<Map.Entry<String ,String>>entrySet = map1.entrySet();
//        Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
//        while (iterator.hasNext()) {
//            Map.Entry<String, String> next = iterator.next();
//            System.out.println(next.getKey());
//            //System.out.println(next.getValue());
//            System.out.println();
//        }

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值