java 对象流

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;


public class ObjectDemo 
{


public static void main(String[] args) {
testObjectOutputStream();
testObjectInputStream();
}
//对象的反序列化,将硬盘中的文件提供ObjectInputStream转换为需要的对象;
public static void testObjectInputStream()
{
ObjectInputStream ois = null;
try{
ois = new ObjectInputStream(new FileInputStream("d:\\a\\a.txt"));
Person p1 = (Person)ois.readObject();
System.out.println(p1);
Person p2 = (Person)ois.readObject();
System.out.println(p2);
} catch (FileNotFoundException e) 
{
e.printStackTrace();
} catch (ClassNotFoundException e) 
{
e.printStackTrace();
} catch (IOException e) 
{
e.printStackTrace();
}finally
{
if(ois != null)
{
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//对象的序列化过程,将内存中的对象通过ObjectOutputStream转换为二进制流,存储在硬盘文件中;
public static void testObjectOutputStream()
{
Person p1 = new Person("xiao", 23);
Person p2 = new Person("da", 21);

ObjectOutputStream oos = null;
try 
{
oos = new ObjectOutputStream(new FileOutputStream(new File("d:\\a\\a.txt")));
oos.writeObject(p1);
oos.flush();
oos.writeObject(p2);
oos.flush();
} catch (FileNotFoundException e) 
{
e.printStackTrace();
} catch (IOException e) 
{
e.printStackTrace();
}finally
{
if(oos != null)
{
try 
{
oos.close();
} catch (IOException e) 
{
e.printStackTrace();
}
}
}
}
}
class Person implements Serializable   //实现Serializable接口
{
//实现Serializable接口的类都有一个UID;
private static final long serialVersionUID = 24367;
String name;
Integer age;
public Person(String name, Integer age)
{
this.name = name;
this.age = age;
}
@Override
public String toString() 
{
return "name" + this.name + "age" +this.age;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值