【问题标题】:Difficulty writing object to file难以将对象写入文件
【发布时间】:2016-12-02 22:13:46
【问题描述】:

我正在尝试从 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");
}

【问题讨论】:

  • 打印异常的堆栈跟踪:e.printStackTrace()。这将告诉您遇到的问题。
  • 我建议处理数据并保存,例如作为文本文件而不是使用ObjectOutputStream。您可以进行循环,将数据保存到数组中,然后以一种可以让您再次正确读取它们的方式保存它们。
  • 捕获各种异常然后将它们作为基本异常抛出没有真正意义。要么处理这些异常,要么让你的方法抛出那些特定的异常,或者干脆throws Exception,如果你不在乎它们是什么类型的话。如果您打印异常的堆栈跟踪,那么您将看到问题所在。
  • 另外,提示:使用 try-with-resource 块而不是显式关闭流。
  • 在这里也包含您的Student 课程可能很有用。

标签: java serialization fileoutputstream


【解决方案1】:

我同意@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 中提取的数据直接写入文件

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-04-13
      • 2015-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      相关资源
      最近更新 更多