1、@Testpublic void test05() throws Exception{//创建一个文件File file=new File("d.txt");//文件输出流FileOutputStream fos=new FileOutputStream(file);String str="你好";//缓存流BufferedOutputStream bos=new BufferedOutputStream(fos);fos.write(str.getBytes());fos.close();}
2、@Testpublic void test06() throws Exception{//文件的序列化//创建一个map集合Map<Integer,String>maps=new HashMap<Integer,String>();//向集合中添加数据maps.put(1, "a");maps.put(2, "b");
3、//创建文件保存数据,从API中可以了解到FileOutputStream的构造函数有这个,true代表追加,FileOutputStrea罪焐芡拂m fos=new FileOutputStream("d.txt",true);//文件的序列化ObjectOutputStream oos=new ObjectOutputStream(fos);//writeObject 方法用于将对象写入流中。所有对象(包括 String 和数组)都//可以通过 writeObject 写入。oos.writeObject(maps);oos.close();}
4、@Testpublic void tesr07() throws Exception{FileInputStream fis=new Fi造婷用痃leInputStream("d.txt");ObjectInputStream ois=new ObjectInputStream(fis);readObject 方法用于从流读取对象。应该使用 Java 的安全强制转换来获取所需的类型。在 Java 中,字符串和数组都是对象,所以在序列化期间将其视为对象。读取时,需要将其强制转换为期望的类型。Map maps=(HashMap)ois.readObject();ois.close();
5、//map集合的遍历,有三种方式,此为其中一种Set<Map.Entry<Integer,String>>sets=maps.entrySet();for(Map.Entry<Integer, String> s:sets){System.out.println("key="+s.getKey()+"value="+s.getValue());}}
6、readObject 方法用于从流中读取对象。应该使用 Java 的安全强制转换来获取所需的类型。在 Java 中,字符串和数组都是对象,所以在序列化期间将其视为对象。读取时,需要将其强制转换为期望的类型。readObject 方法用于从流中读取对象。在 Java 中,字符串数组和集合都是对象,所以在序列化期间将其视为对象。读取时,需要将其强制转换为期望的类型。