关于存储、读入Object,贴两个方法

本文提供了两种用于操作Java中对象的方法:一种是将对象写入指定路径的文件中,另一种是从指定路径的文件中读取对象。这两种方法依赖于对象实现了序列化接口,并且能够通过ObjectInputStream和ObjectOutputStream进行序列化和反序列化。文章还提到了如何判断返回的Object对象的具体类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

生成.sdua文件的时候可能会用到读写对象,贴两个方法……

  /**写对象方法,参数是路径和对象*/

    public static void writeObject(String outFile, Object object) {
        try {
            ObjectOutputStream out = new ObjectOutputStream(
                    new BufferedOutputStream(new FileOutputStream(outFile)));
            out.writeObject(object);
            out.close();
        } catch (Exception e) {
            System.err.println(e);
        }
    }
    
  /**写对象方法,参数是对象路径,返回Object对象*/
    public static Object readObject(String filePath) {
        File inFile = new File(filePath);
        if(!inFile.exists()){
            return null;
        }
        Object o = null;
        try {
            ObjectInputStream in = new ObjectInputStream(
                    new BufferedInputStream(new FileInputStream(inFile)));
            o = in.readObject();
            in.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        return o;
    }

另外,

1、需要读写的对象需要实现序列化接口(

  1. xxxx implements Serializable
 )

2、返回Object可以用instanceoff关键字判断是否是某一种对象,例如

if(object instanceof int[]){

System.out.println("length of the arr is : "+ ((int[])object).length);

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值