JAVA高手帮帮忙!!!JAVA的序列化问题!!!
答案:1 悬赏:10 手机版
解决时间 2021-05-04 15:52
- 提问者网友:放下
- 2021-05-03 16:15
定义一个可序列化的对象Student类,这个类实现了Serializable接口,类中的成员变量id,name,age,department都可以被序列化,方法不能序列化。通过对象输出流的writeObject()方法将Student对象保存到文件data.ser中,然后通过对象输入流的readObject()方法从文件data.ser中读出保存下来的Student对象,然后将Student对象的id和name输出到控制台。
最佳答案
- 五星知识达人网友:罪歌
- 2021-05-03 16:59
import java.io.*;
class Student implements Serializable {
static private final long serialVersionUID = 123L;
int id;
String name;
int age;
String department;
public Student(int i, String n, int a, String d) {
id = i; name = n; age = a; department = d;
}
public String toString() {
return id + " " + name + " " + age + " " + department;
}
}
public class test {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectOutputStream o =
new ObjectOutputStream(new FileOutputStream("D:\\sss.txt"));
o.writeObject(new Student(123, "C君", 18, "X部门"));
o.close();
ObjectInputStream i =
new ObjectInputStream(new FileInputStream("D:\\sss.txt"));
System.out.println(((Student)i.readObject()).toString());
i.close();
}
}
class Student implements Serializable {
static private final long serialVersionUID = 123L;
int id;
String name;
int age;
String department;
public Student(int i, String n, int a, String d) {
id = i; name = n; age = a; department = d;
}
public String toString() {
return id + " " + name + " " + age + " " + department;
}
}
public class test {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectOutputStream o =
new ObjectOutputStream(new FileOutputStream("D:\\sss.txt"));
o.writeObject(new Student(123, "C君", 18, "X部门"));
o.close();
ObjectInputStream i =
new ObjectInputStream(new FileInputStream("D:\\sss.txt"));
System.out.println(((Student)i.readObject()).toString());
i.close();
}
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯