对象流——序列化 FileInputStream(f) ObjectInputStream(fis)

注:把一个对象序列化有一个前提是:这个对象的类,必须实现了Serializable接口

public static void main(String[] args) {
        //创建一个Hero garen
        //要把Hero对象直接保存在文件上,务必让Hero类实现Serializable接口
        Hero h = new Hero();
        h.name = "garen";
        h.hp = 616;
          
        //准备一个文件用于保存该对象
        File f =new File("d:/garen.lol");
 
        try(
            //创建对象输出流
            FileOutputStream fos = new FileOutputStream(f);
            ObjectOutputStream oos =new ObjectOutputStream(fos);
            //创建对象输入流              
            FileInputStream fis = new FileInputStream(f);
            ObjectInputStream ois =new ObjectInputStream(fis);

        ) {
            oos.writeObject(h);//现在f的文件里保存了这个对象
            Hero h2 = (Hero) ois.readObject();//在将它读取出来
            System.out.println(h2.name);
            System.out.println(h2.hp);
               
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            
    }

猜你喜欢

转载自blog.csdn.net/Whiteleaf3er/article/details/82557271
今日推荐