java—序列化中的追加

8dtrkrch  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(307)

到目前为止,我发现有一种方法可以通过生成子类来进行序列化中的追加,但这似乎是一种冗长的方法。有没有更好的方法在序列化中进行追加?
我在一个名为course的类中有一个向量列表 private Vector<Student> StudentList = new Vector<>(); 我当然有两个目标。一门课程招收3名学生,另一门课程招收2名学生。现在我调用这个在文件中进行序列化的方法,但是当我用我的第二个course对象调用它时,它会替换以前的内容。

public void Serialization() {
        try {
            File file = new File("EnrolledStudentsSerial.txt");
            if(!file.exists()){
               file.createNewFile();
            }
            FileOutputStream fo = new FileOutputStream(file);
            ObjectOutputStream output = new ObjectOutputStream(fo);
            output.writeObject("Course: " + this.name + "\n\nEnrolled Students: ");
            for (int i = 0; i < StudentList.size(); i++) {
                Student p_obj = StudentList.elementAt(i);
                String content = "\n\tStudent Name: " + p_obj.getName() + "\n\tStudent Department: " + p_obj.getDepartment() + "\n\tStudent Age: " + p_obj.getAge() + "\n";
                output.writeObject(content);
            }
            output.writeObject("\n");
            fo.close();
        } catch (IOException ioe){
            System.out.println("Error: " + ioe.getMessage()); 
        }
    }
waxmsbnn

waxmsbnn1#

如果要附加到文件,而不是替换内容,则需要告诉 FileOutputStream 通过添加一个额外的参数和调用 FileOutputStream(File file, boolean append) . 仅供参考:不要用 ObjectOutputStream .
你不需要打电话 createNewFile() ,自 FileOutputStream 会这样做,不管是否附加。
但是,实际上并不是序列化对象,而是序列化字符串。你这样做毫无意义。因为您似乎希望结果是一个文本文件(您正在编写文本,而文件名是 .txt ),你应该忘记 ObjectOutputStream ,并使用 FileWriter 相反。
更好的是,您应该使用Java7中添加的“更新的”nio.2API,而不是使用旧的文件i/OAPI。您还应该使用try with资源。古人也是如此 Vector 类,替换为 ArrayList 在Java1.2中。
java命名约定是字段和方法名以小写字母开头。既然你的方法不再“序列化”,你应该给它一个更好的名字。
应用所有这些,您的代码应该是:

import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.WRITE;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
private ArrayList<Student> studentList = new ArrayList<>();
public void writeToFile() {
    Path file = Paths.get("EnrolledStudentsSerial.txt");
    try (BufferedWriter output = Files.newBufferedWriter(file, CREATE, APPEND, WRITE)) {
        output.write("Course: " + this.name + "\n\nEnrolled Students: ");
        for (Student student : studentList) {
            String content = "\n\tStudent Name: " + student.getName() +
                             "\n\tStudent Department: " + student.getDepartment() +
                             "\n\tStudent Age: " + student.getAge() + "\n";
            output.write(content);
        }
        output.write("\n");
    } catch (IOException ioe){
        System.out.println("Error: " + ioe.getMessage()); 
    }
}

相关问题