import java.io.*;
/**
* Java 序列化
* Java 提供了一种对象序列化的机制,该机制中,一个对象可以被表示为一个字节序列,该字节序列包括该对象的数据、有关对象的类型的信息和存储在对象中数据的类型。
*
* 将序列化对象写入文件之后,可以从文件中读取出来,并且对它进行反序列化,也就是说,对象的类型信息、对象的数据,还有对象中的数据类型可以用来在内存中新建对象。
*/
public class Obj6 {
public static void main(String[] args) {
Employe e = new Employe();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try{
FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in /tmp/employee.ser");
}catch (IOException i)
{
i.printStackTrace();
}
Employe e_ = null;
try
{
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInput in = new ObjectInputStream(fileIn);
e_ = (Employe) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e_.name);
System.out.println("Address: " + e_.address);
System.out.println("SSN: " + e_.SSN);
System.out.println("Number: " + e_.number);
}
}
标签:Java,对象,System,println,new,序列化,out From: https://blog.51cto.com/u_15826214/5750140