package SerializationAndDesserialization;//序列化和反序列化
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.OutputStream;
import java.io.Serializable;
import java.nio.channels.FileChannel;
import javax.swing.JFileChooser;
/**
* 对象的序列化和反列化
*
* @author 李。文
* @version 1.8
* @date 2019年8月6日 上午8:44:40
* @content JAVA代码
* @motto 代码千万条,可读第一条。代码不规范,error多两行。
*/
public class ObjectIODemo {
public static final String filePath = "c://test";
public static void main(String[] args) {
Player player = new Player("王炸", 5000, 1000);
JFileChooser fileChoose = new JFileChooser(filePath);
fileChoose.showOpenDialog(null);
File file = fileChoose.getSelectedFile();
try(
FileOutputStream outputStream = new FileOutputStream(file);
ObjectOutputStream objoutStream = new ObjectOutputStream(outputStream);
)
{ // 将对象写入到指定文件中去
objoutStream.writeObject(player);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("对象的已经写入到指定文件" + file.getName() + "中去");
}
// 进行反序列化
fileChoose.showOpenDialog(null);
File file1 = fileChoose.getSelectedFile();
Player player1 =null;
try (FileInputStream inputSteam = new FileInputStream(file1);
ObjectInputStream obinStream = new ObjectInputStream(inputSteam);) {
// 简单读取的对象赋值给一个新的对象
try {
player1 = (Player) obinStream.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("读取玩家的信息为"+player1);
}
}
}
class Player implements Serializable {
// 序列号
private static final long serialVersionUID = 7906103700322856644L;
private int level; // 玩家的等级
private String name;// 玩家的名称
private int health;// 玩家的健康值
// 构造方法
public Player() {
}
public Player(String name, int level, int health) {
this.setHealth(health);
this.setLevel(level);
this.setName(name);
}
// 重写接口的toString方法
@Override
public String toString() {
return getName() + "\t" + getHealth() + "\t" + getLevel();
}
// 创建方法
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
对象IO(序列化和反序列化)进行了对象的读写操作
最新推荐文章于 2022-06-05 00:38:29 发布