/**
* 对象的序列化和反序列化
*/
package objectinput_output_stream;
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.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class save_object {
private static final String filepath = "C:/java_practice/存档.txt";
public static void main(String[] args) {
Player player = new Player("zouxu",999);
File file = new File(filepath);
FileOutputStream foutstream = null;
try {
foutstream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ObjectOutputStream objoutstream = null;
try {
objoutstream = new ObjectOutputStream(foutstream);
} catch (IOException e) {
e.printStackTrace();
}
try {
objoutstream.writeObject(player);
} catch (IOException e) {
e.printStackTrace();
}
try {
objoutstream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
foutstream.close();
} catch (IOException e) {
e.printStackTrace();
}
FileInputStream finputstream = null;
try {
finputstream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ObjectInputStream objinputstream = null;
try {
objinputstream = new ObjectInputStream(finputstream);
} catch (IOException e) {
e.printStackTrace();
}
Player player2 = null;
try {
player2 = (Player) objinputstream.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
objinputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
finputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(player2.getName());
}
}
class Player implements Serializable {
private static final long serialVersionUID = 1L;
public String name;
public int level;
public Player(){
}
public Player(String name,int level)
{
setName(name);
setLevel(level);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}