java - how to add an arraylist of objects to file -
i want write program have sign , sign in button. if user press sign button username , password must written file. have problem in appending file. have arraylist of object(user) called people, , add arraylist file. when print contents of file see first user, , if print arraylist, has 1 object last one. here addmethod in class:
public class addtofile { arraylist<user> people = new arraylist<user>(); user user; public void add(string username, string password) throws filenotfoundexception, ioexception, classnotfoundexception { user u1 = new user(username, password, "hello", null, null, null); fileoutputstream fout = new fileoutputstream("f.txt", true); objectoutputstream out = new objectoutputstream(fout); people.add(u1); system.out.println(people.size()); (user people1 : people) { system.out.println("user " + people1.username + " pass " + people1.password); } (user p : people) { out.writeobject(p); } out.flush(); out.close(); system.out.println("success"); objectinputstream = new objectinputstream(new fileinputstream("f.txt")); user u = (user) is.readobject(); system.out.println("file user :" + u.username + " pass:" + u.password); is.close(); } }
that user class implements serializable.
you can have multiple files each objects (user) , keep in directory different file names. using directory file name reader method, can read files names in directory. read each files , convert user objects. don't think append object stream work.
arraylist<user> people = new arraylist<user>(); user user; user u1 = new user(username, password, "hello", null, null, null); people.add(u1); system.out.println(people.size()); (user people1 : people) { system.out.println("user " + people1.username + " pass " + people1.password); } (user p : people) { fileoutputstream fout = new fileoutputstream("/tempobjects/" + p.getusername(), true); // assume user name unique objectoutputstream out = new objectoutputstream(fout); out.writeobject(p); out.flush(); out.close(); } system.out.println("success"); file folder = new file("/tempobjects/"); //reading folder file[] listoffiles = folder.listfiles(); // file names in folder (int = 0; < listoffiles.length; i++) { // reading each file details if (listoffiles[i].isfile()) { objectinputstream = new objectinputstream(new fileinputstream(listoffiles[i].getname())); user u = (user) is.readobject(); system.out.println("file user :" + u.username + " pass:" + u.password); is.close(); } }
Comments
Post a Comment