难以将对象写入文件

时间:2016-07-28 13:23:38

标签: java serialization fileoutputstream

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

2 个答案:

答案 0 :(得分:0)

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

即可

答案 1 :(得分:0)

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