定义一个类的对象,将此类的属性输入到一个文件中,还能读出来,求解!
将对象保存到文件,后续还可以使用。这个操作称为序列化(Serialization)。
对象能够序列化,必须继承 Serializable 接口。
代码直接给你吧,应该能看懂不吧
public class NewBean {
public static void main(String[] args) {
ObjectOutputStream ob;
OutputStream out;
InputStream in;
ObjectInputStream ib;
Demo1 demo = new Demo1();
demo.setAge(12);
demo.setName("zs");
File f = new File("你的文件存放路径");
try {
out = new FileOutputStream(f);
ob = new ObjectOutputStream(out);
ob.writeObject(demo);
in = new FileInputStream(f);
ib = new ObjectInputStream(in);
Demo1 o = (Demo1)ib.readObject();
System.out.println("姓名:"+o.getName()+"; 年龄:"+o.getAge());
//记得关闭流
in.close();
ib.close();
ob.close();
out.close();
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Demo1 implements Serializable{
private String name;
private int age;
public Demo1(){}
public Demo1(String name,int age){
this.age = age;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}