java - Difficulty writing object to file -


i'm trying read map of students txt file, after add new student map (now bigger before) , save file. after close program , reload data file, new students weren't saved.

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 not created"); } catch (classnotfoundexception e) {     throw new exception("class not found excpetion"); } 

i agree @xdevs23

instead of saving data arrays (which use more memory), write

/*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 hash keys     for(int = 0; < studentobj.size(); i++){        w.write(studentobj.get(i).getstring());        w.write(studentobj.get(i).getstudent());     }      w.close();        catch (ioexception e) {         throw new exception("file not created");     } catch (classnotfoundexception e) {         throw new exception("class not found excpetion");     } } 

and write data pulled objectinputstream directly file


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -