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
Post a Comment