java的序列化和反序列化

本文详细介绍了如何使用Java进行对象的序列化和反序列化操作,通过具体示例代码展示了序列化过程,即将对象状态转换为字节流以便存储或传输,以及反序列化过程,即从字节流中恢复对象状态。文章覆盖了必要的异常处理,并提供了完整的代码实现。

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

package com.lideng.work325;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
 * 序列化和反序列化
 * @author Administrator
 *
 */
public class Demo05  implements Serializable{

	public static void main(String[] args) {
		try {
			test01("c:/Test.java");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 反序列化
	 * @param file
	 * @throws Exception
	 */
	public static void test01(String file) throws Exception{
		ObjectInputStream os=new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
		Object obj = os.readObject();
		System.out.println(obj);
		int[] num=(int[])obj;
		for (int i = 0; i < num.length; i++) {
			System.out.println(num[i]);
		}
		
	}
	/**
	 * 序列化
	 * @param file
	 * @throws Exception
	 */
	public static void test(String file) throws Exception{
		
		int [] num={5,8,9,4,8};
		
		ObjectOutputStream os=new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(file)));
		os.writeObject(num);
		os.flush();
		os.close();
	}
}

  

转载于:https://www.cnblogs.com/qurui1997/p/10609841.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值