难以将对象写入文件

Difficulty writing object to file

我正在尝试从 txt 文件中读取学生地图,然后我将新学生添加到地图(现在比以前大)并将其保存回文件。在我关闭我的程序并从文件中重新加载数据后,新学生没有被保存。

HashMap<String, Student> studentObj = new HashMap<>(SIZE);

try {
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(DEFAULT_FILE_NAME)); 
    studentObj = (HashMap<String, Student>) in.readObject();            
    studentObj.put(student.getStudentID(), student);

    ObjectOutputStream out;
    out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(DEFAULT_FILE_NAME)));
    out.writeObject(studentObj);
    out.flush();
    System.out.println("here " + studentObj.size());
    in.close();
    out.close();
} catch (IOException e) {
    throw new Exception("FILE IS NOT CREATED");
} catch (ClassNotFoundException e) {
    throw new Exception("CLASS NOT FOUND EXCPETION");
}

我同意@xdevs23

您可以这样写

,而不是将数据保存到数组中(这将使用更多内存)
/*import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;*/

HashMap<String, Student> studentObj = new HashMap<>(SIZE);

try{

    ObjectInputStream in = new ObjectInputStream(new FileInputStream(DEFAULT_FILE_NAME)); 
    studentObj = (HashMap<String, Student>) in.readObject();            
    studentObj.put(student.getStudentID(), student);
    in.close();
    System.out.println("here " + studentObj.size());

    FileOutputStream fos = new FileOutputStream(DEFAULT_FILE_NAME);
    OutputStreamWriter osw = new OutputStreamWriter(fos);
    Writer w = new BufferedWriter(osw);

    // Iterate using YOUR hash keys
    for(int i = 0; i < studentObj.size(); i++){
       w.write(studentObj.get(i).getString());
       w.write(studentObj.get(i).getStudent());
    }

    w.close();

      catch (IOException e) {
        throw new Exception("FILE IS NOT CREATED");
    } catch (ClassNotFoundException e) {
        throw new Exception("CLASS NOT FOUND EXCPETION");
    }
}

并且直接将ObjectInputStream拉取的数据写入文件即可

我的代码没问题。问题是将对象保存到文件后,我关闭了应用程序并再次打开它。然后,构造函数创建了一个覆盖旧文件的新文件。我添加了一个 if 语句来第一次创建文件。我使用 txt 使它变得简单和快速,因为这只是一个小任务。我喜欢使用 xml 文件来代替 :) 是的,JAVA 可以保存对象。