【高级API】(序列化&反序列化)

本文介绍了Java中文件的基本操作,包括文件复制和剪切的方法,并深入探讨了对象的序列化与反序列化过程,展示了如何保存和读取对象到文件。

--文件的复制and剪切
        File file = new File("f:\\图片\\0809.txt");
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        byte[] bs = new byte[(int)file.length()];
        bis.read(bs);
        bis.close();
        fis.close();
        
        File newF = new File("f:\\0105.txt");
        FileOutputStream fos = new FileOutputStream(newF);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bos.write(bs);
        bos.close();
        fos.close();

        file.delete();
        System.out.println("ok");

之前我们操作的只能是字符串 今天我们要学读写的高级类
--序列化and反序列化
在实际工作中,可以把数据从硬盘的介质中导入 还可以从内存中导出去

//序列化:把一个对象从内存中存放到硬盘中的过程
//所有要序列化的类都必须实现Serializable接口
        Dog d=new Dog("来福1","公",23);
        File file = new File("f:\\图片\\dog1");
        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(d);

//关闭必须由内而外!
        oos.close();
        bos.close();
        fos.close();
        System.out.println("ok");
        
//反序列化:将对象从硬盘介质中还原到内存中
        File file = new File("f:\\图片\\dog");
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        ObjectInputStream ois = new ObjectInputStream(bis);
        Dog d = (Dog)ois.readObject();
        System.out.println(d.getName());
        ois.close(); 
        bis.close();
        fis.close();

保存1000只狗 
        ArrayList<Dog> dogs = new ArrayList<Dog>();
        for (int i = 0; i < 1000; i++) {
            Dog d = new Dog("旺财"+i, "公", i+1);
            dogs.add(d);
        }
        
        File file = new File("f:\\图片\\dogs.bak");
        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(dogs);
        oos.close();
        bos.close();
        fos.close();
        System.out.println("完美?");

是不是所有实现序列化的类都必须实现Serializable接口?那么arrayList集合捏?Dog还有没有必要?

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值