用java中objectoutputstream写一个储存和输出信息的代码
时间: 2023-05-20 10:06:11 浏览: 65
好的,以下是一个用Java中ObjectOutputStream写储存和输出信息的代码示例:
```java
import java.io.*;
public class ObjectOutputExample {
public static void main(String[] args) {
try {
// 创建一个ObjectOutputStream对象
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.txt"));
// 创建一个Person对象
Person person = new Person("张三", 20);
// 将Person对象写入到文件中
out.writeObject(person);
// 关闭ObjectOutputStream
out.close();
// 创建一个ObjectInputStream对象
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.txt"));
// 从文件中读取Person对象
Person p = (Person) in.readObject();
// 输出Person对象的信息
System.out.println("姓名:" + p.getName() + ",年龄:" + p.getAge());
// 关闭ObjectInputStream
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
这个代码示例中,我们创建了一个Person类,实现了Serializable接口,这样我们就可以将Person对象序列化到文件中。然后我们创建了一个ObjectOutputStream对象,将Person对象写入到文件中。接着我们创建了一个ObjectInputStream对象,从文件中读取Person对象,并输出其信息。最后我们关闭了ObjectOutputStream和ObjectInputStream对象。