import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Person implements Serializable
{
private static final long serialVersionUID = -3569622348945012472L;
private String name; // 设置transient,name不会被序列化
private int age;
private transient String sex;
private String type = "美国";
public Person(String name, int age, String sex, String type){
this.name = name;
this.age = age;
this.sex = sex;
this.type = type;
}
public String toString()
{
return " 姓名:" + this.name +
";年龄:" + this.age +
";性别:" + this.sex +
";国家:" + this.type;
}
}
public class Test
{
public static void main(String[] args) throws Exception
{
ser();
dser();
}
public static void ser() throws Exception
{
File f = new File("E:" + File.separator + "ss.txt");
OutputStream out = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(out);
Person per1[][] = {{new Person("张一", 30, "男", "美国"),
new Person("张二", 31, "女", "美国"),
new Person("张三", 32, "男", "俄罗斯")},
{new Person("王一", 40, "男", "美国"),
new Person("王二", 41, "男", "美国"),
new Person("王五", 42, "女", "俄罗斯")}};
oos.writeObject(per1);
oos.flush();
oos.close();
out.close();
}
public static void dser() throws Exception
{
File f = new File("E:" + File.separator + "ss.txt");
InputStream ipt = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(ipt);
Object ps = ois.readObject();
if(ps != null)
{
for(Object o : (Object[][])ps)
{
for(Object p : (Object[])o)
{
System.out.print(p);
}
System.out.println();
}
}
ois.close();
ipt.close();
}
}
Java对象序列化
最新推荐文章于 2024-10-09 09:36:43 发布