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());
}
}
}
}