Java JPA write object to binary file -


  • database (user)
    id     name
    1         ali
    2        abu
    3      ahmad

  • writebinaryfile.java

    entitymanagerfactory emf = persistence.createentitymanagerfactory("userpu"); entitymanager em = emf.createentitymanager();  query query1 = em.createnativequery("select * user",user.class); list<user> list = query1.getresultlist();  for(user userlist: list){     fileoutputstream fos = new fileoutputstream("test.dat");     objectoutputstream oos = new objectoutputstream(fos);      oos.writeobject(userlist);     oos.close(); } 
  • readbinaryfile.java

    fileinputstream fis = new fileinputstream("test.dat"); objectinputstream ois = new objectinputstream(fis);  user user1 = (user) ois.readobject(); ois.close(); system.out.println(user1.getid+" "+user1.getname()); 
  • when read readbinaryfile.java, can output following:
    3 ahmad

  • my expected output:
    1 ali
    2 abu
    3 ahmad

  • what doing wrong? how can solve it?

aren't overwriting file on each loop?

for(user user: list){     //overwrites file on each loop     fileoutputstream fos = new fileoutputstream("test.dat");     objectoutputstream oos = new objectoutputstream(fos);      oos.writeobject(user);     oos.close(); } 

you need either create new file each user or write entire list , read in.

fileoutputstream fos = new fileoutputstream("test.dat"); objectoutputstream oos = new objectoutputstream(fos);  oos.writeobject(list); oos.flush(); oos.close();   fileinputstream fis = new fileinputstream("test.dat"); objectinputstream ois = new objectinputstream(fis);  list<user> users = (list<user>) ois.readobject(); ois.close();  for(user user : users){     system.out.println(user.getid() +" " + user.getname()); } 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -