Java学习笔记——测试三

1. 设计遍历HashMap的方法,使用键值对象集遍历,分别得到键和值输出
2. 设计日期解析的方法,传入日期类型字符串如”2020-08-01”或”2020年08月01日”,将其解析会日期对象并返回
3. 利用 FileInputStream 和FileOutputStream,完成下面的要求:
1)用 FileOutputStream
在当前目录下创建一个文件“test.txt”,并向文件输出“Hello World”,如果文件已存在,则在原有文件内容后面追加。
2)用FileInputStream 读入test.txt 文件,并在控制台上打印出test.txt 中的内容。
3) 要求用try-catch-finally 处理异常,并且关闭流应放在 finally 块中。

package javatest;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Main m = new Main();
        HashMap<String,Boolean> h = new HashMap<>();
        h.put("a",true);
        m.test10(h);
        System.out.println(m.test11("2002/03/04"));
        m.test12();
    }

    public void test10(HashMap hm){
        Set<Map.Entry> set = hm.entrySet();
        for(Map.Entry e : set){
            System.out.println(e.getKey().toString());
            System.out.println(e.getValue().toString());
        }
    }

    public Date test11(String str){
        Date date = new Date();
        String[] strs = str.split("[0-9]");
        StringBuffer p = new StringBuffer("yyyyMMdd");
        int i = 4;
        for (String s : strs){
            if (!Objects.equals(s, "")){
                p.insert(i,s);
                i += (2 + s.length());
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat(p.toString());
        try {
            date = sdf.parse(str);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return date;
    }

    public void test12(){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try{
            fos = new FileOutputStream("test.txt",true);
            String s = "Hello Word";
            fos.write(s.getBytes());

            fis = new FileInputStream("test.txt");
            byte[] bytes = new byte[fis.available()];
            fis.read(bytes);
            for(byte c : bytes){
                System.out.print((char)c);
            }
            System.out.println();
        }catch(Exception e){
            System.out.println(e.getMessage());
        }finally{
            try {
                fis.close();
                fos.close();
            }catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值