gpt4 book ai didi

java - 如何序列化/反序列化java中的对象列表?

转载 作者:行者123 更新时间:2023-12-01 06:40:00 25 4
gpt4 key购买 nike

如何在 Java 中序列化可序列化类的多个对象?

例如

public class Personne implements java.io.Serializable {

String nom;
String date;

Personne(String nom,String date)
{
this.nom=nom;
this.date=date;
}
}

我想创建许多对象:

Personne p1 = new  Personne("X","XX");
Personne p2 = new Personne("Y","ZZ");
Personne p3 = new Personne("Z","ZZ");

--> 序列化这些对象的静态函数

--> 反序列化静态函数

完整代码:

package game2;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
*
* @author ahmedJ
*/
public class Personne implements java.io.Serializable {

String nom;
String date;

Personne(String nom, String date) {
this.nom = nom;
this.date = date;
}

public static void Serialiser(Personne sp) {

try {
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("Score.sp"));
out.writeObject(sp);
out.flush();
out.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}

public static void Deserialiser() {

Personne a1, a2, a3;
try {
FileInputStream file = new FileInputStream("Score.sp");
ObjectInputStream in = new ObjectInputStream(file);
a1 = (Personne) in.readObject();
a2 = (Personne) in.readObject();
a3 = (Personne) in.readObject();

System.out.println(a1.nom);
System.out.println(a2.nom);
System.out.println(a3.nom);

in.close();
file.close();
} catch (Exception ex) {
System.err.println("Erreur de lecture " + ex);
}

}

public static void main(String[] sd) {
Personne p1 = new Personne("X", "XX");
Personne p2 = new Personne("Y", "ZZ");
Personne p3 = new Personne("Z", "ZZ");

Serialiser(p1);
Serialiser(p2);
Serialiser(p3);

Deserialiser();
}
}

最佳答案

使用ObjectOutputStream写和 ObjectInputStream读书。非常简单并且有效:

  ObjectOutputStream out = new ObjectOutputStream(myFileOutputStream);
out.writeObject(p1);
out.writeObject(p2);
out.writeObject(p3);
out.close();
....
ObjectInputStream in = new ObjectInputStream(myFileInputStream);
p1 = (Personne) in.readObject();
p2 = (Personne) in.readObject();
p3 = (Personne) in.readObject();

关于java - 如何序列化/反序列化java中的对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14655926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com