java将对象写入txt文件
时间: 2024-05-12 13:16:48 浏览: 147
可以使用Java的ObjectOutputStream将对象写入二进制文件,然后使用BufferedWriter将二进制文件转换为文本文件。以下是一个示例代码:
```
import java.io.*;
public class WriteObjectToFile {
public static void main(String[] args) {
// Create an instance of the object you want to serialize
// For example, a Person object with name and age fields
Person person = new Person("John Doe", 30);
try {
// Create a new ObjectOutputStream to write the object to a binary file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.bin"));
// Write the object to the binary file
out.writeObject(person);
out.close();
// Convert the binary file to a text file using BufferedFile and FileWriter
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("person.bin")));
FileWriter fw = new FileWriter("person.txt");
String s;
while((s = in.readLine()) != null) {
fw.write(s);
}
in.close();
fw.close();
} catch (IOException 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;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
```
阅读全文