write object to file java -
i creating application manages agenda. each contact must written in object file. how can check if file exists , there way write next object without overwriting??
my class:
import java.io.*; public class writefile { public void setcontact(agenda contact){ objectoutputstream out; try{ file file = new file("contacts.txt"); out = new objectoutputstream(new fileoutputstream(file)); out.writeobject(contact); out.flush(); out.close(); system.out.println("object written file"); } catch (filenotfoundexception ex) { system.out.println("error specified file") ; ex.printstacktrace(); } catch (ioexception ex) { system.out.println("error i/o processes") ; ex.printstacktrace(); } } }
using code, believe easiest thing make use of file.exists() method check see if file exists.
boolean exists = file.exists();
then can use following constructor the fileoutputstream:
public fileoutputstream(file file, boolean append) throws filenotfoundexception
to append end of file. construction of object should wrapped in if-else clause, depending on value of file.exists().
Comments
Post a Comment