码迷,mamicode.com
首页 > 编程语言 > 详细

java 对象序列化

时间:2014-05-03 21:44:57      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:java对象序列化

bubuko.com,布布扣

上代码

/**
 * Person.java
 */
import java.io.*;

public class Person implements Serializable
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String name;
	private int age;
	
	public Person(String str,int num)
	{
		name=str;
		age=num;
	}
	public String toString()
	{
		return "Name:"+name+"\tAge:"+age;
	}
}
/**
 * SerializableDemo.java
 */
import java.io.*;

public class SerializableDemo
{
	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException
	{
		Person pers=new Person("cjc",24);
		File f=new File("F:\\workspace\\JavaPrj\\test.txt");
		serial(pers,f);
		deserial(f);
	}
	public static void serial(Object p,File f) throws FileNotFoundException, IOException
	{
		ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(f));
		out.writeObject(p);
		out.close();
	}
	public static void deserial(File f) throws FileNotFoundException, IOException, ClassNotFoundException
	{
		ObjectInputStream in=new ObjectInputStream(new FileInputStream(f));
		Person p=(Person)in.readObject();
		in.close();
		System.out.println(p);
	}
}
bubuko.com,布布扣

另外,如果不希望类中的属性被序列化,可以在声明属性之前加上transient关键字

将name属性修改为transient,即private transient String name;
bubuko.com,布布扣

java 对象序列化,布布扣,bubuko.com

java 对象序列化

标签:java对象序列化

原文地址:http://blog.csdn.net/cjc211322/article/details/24921173

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!