1 /** 2 * 针对对象的文件读写 3 */ 4 5 //导入包 6 import java.io.File; 7 import java.io.FileInputStream; 8 import java.io.FileNotFoundException; 9 import java.io.FileOutputStream; 10 import java.io.IOException; 11 import java.io.ObjectInputStream; 12 import java.io.ObjectOutputStream; 13 import java.util.HashMap; 14 15 public class qwe { 16 17 public static void main(String[] args) { 18 try { 19 File f = new File("D:\\Desktop\\NewFile\\hasKey.txt");//关联文件 20 FileOutputStream wr = new FileOutputStream("D:\\Desktop\\NewFile\\hasKey.txt");//文件写 21 ObjectOutputStream objw = new ObjectOutputStream(wr);//创建对象输出流 22 FileInputStream re = new FileInputStream("D:\\Desktop\\NewFile\\hasKey.txt");//读文件 23 ObjectInputStream objr = new ObjectInputStream(re); //创建对象输入流 24 HashMap<String,String> has = new HashMap<String,String>();//创建集合 25 has.put("001", "hello") ; 26 27 objw.writeObject(has);//从对象输出流中写入 28 HashMap<String, String> has1 = (HashMap<String, String>) objr.readObject();//从对象输入流中读(强制转换类型) 29 30 System.out.println(has1); 31 32 } catch (FileNotFoundException e) {//无文件异常捕获 33 // TODO Auto-generated catch block 34 e.printStackTrace(); 35 } 36 catch (IOException e) {//捕获IO异常 37 // TODO Auto-generated catch block 38 e.printStackTrace(); 39 }catch (ClassNotFoundException e) {//捕获不存在的类型的异常 40 41 e.printStackTrace(); 42 } 43 44 45 } 46 47 }
运行结果为
存入文本的数据是
时间: 2024-10-08 17:30:55