编写Java应用程序,创建一个可序列化类,将该类的对象写入到文件中。用对象输入流读取并显示对象信息。
时间: 2024-03-16 17:42:15 浏览: 13
好的,我会尽力回答你的问题。下面是 Java 应用程序的代码示例:
```java
import java.io.*;
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;
}
}
public class SerializeDemo {
public static void main(String[] args) {
try {
// 创建一个可序列化对象
Person person = new Person("张三", 25);
// 将该对象写入到文件中
FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(person);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in person.ser");
// 用对象输入流读取并显示对象信息
FileInputStream fileIn = new FileInputStream("person.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Person newPerson = (Person) in.readObject();
in.close();
fileIn.close();
System.out.println("Name: " + newPerson.getName());
System.out.println("Age: " + newPerson.getAge());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
这个程序定义了一个可序列化的类 `Person`,并创建了一个 `Person` 对象,将该对象写入到文件 `person.ser` 中。然后,程序用对象输入流读取并显示对象的信息。
你可以将上述代码复制到一个 Java 文件中,编译并运行它,就可以看到程序的输出结果了。