使用对象流写入和读取文件中的对象
时间: 2024-05-15 07:15:36 浏览: 118
java 对象输入输出流读写文件的操作实例
首先,需要创建一个类,该类需要实现Serializable接口,以便对象可以序列化和反序列化。例如,我们创建一个Person类:
```java
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;
private String address;
public Person(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
```
然后,我们可以使用对象输出流将一个Person对象写入文件中:
```java
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("person.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
Person person = new Person("Alice", 25, "123 Main St");
oos.writeObject(person);
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
最后,我们可以使用对象输入流从文件中读取对象:
```java
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("person.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Person person = (Person) ois.readObject();
System.out.println(person);
ois.close();
fis.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
输出结果为:
```
Person{name='Alice', age=25, address='123 Main St'}
```
阅读全文