gpt4 book ai didi

java - 将 Class 对象保存到 Java 中的文本文件

转载 作者:行者123 更新时间:2023-11-29 05:21:36 24 4
gpt4 key购买 nike

Java 初学者,制作了一个学生管理程序,其中有类(class)学生,我想将学生的数据作为对象保存到文本文件中。我尝试使用 Objectoutputstream,但显示文件中的内容以某种尴尬的形式。任何帮助将不胜感激。

最佳答案

您可以尝试下面的示例代码在 Java 中使用 ObjectOutputStream 以便将其写入文件:

import java.io.Serializable;

public class Person implements Serializable {

private String firstName;
private String lastName;
private int age;

public Person() {
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

//Overriding toString to be able to print out the object in a readable way
//when it is later read from the file.
public String toString() {

StringBuffer buffer = new StringBuffer();
buffer.append(firstName);
buffer.append("\n");
buffer.append(lastName);
buffer.append("\n");
buffer.append(age);
buffer.append("\n");

return buffer.toString();
}


}

这是创建 Person 类实例并将它们写入 ObjectOuputStream 的代码:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Main {

/**
* Example method for using the ObjectOutputStream class
*/
public void writePersons(String filename) {

ObjectOutputStream outputStream = null;

try {

//Construct the LineNumberReader object
outputStream = new ObjectOutputStream(new FileOutputStream(filename));

Person person = new Person();
person.setFirstName("James");
person.setLastName("Ryan");
person.setAge(19);

outputStream.writeObject(person);

person = new Person();

person.setFirstName("Obi-wan");
person.setLastName("Kenobi");
person.setAge(30);

outputStream.writeObject(person);


} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectOutputStream
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}


public static void main(String[] args) {
new Main().writePersons("myFile.txt");
}
}

希望您有明确的想法和示例代码。

谢谢。

关于java - 将 Class 对象保存到 Java 中的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24475286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com