Writing to a file from an array list and Vice Versa
I have created a small program with 3 buttons and 1 text field for user
input. What the program does is, it takes input from the user and stores
it to an arraylist, then when the second button is pressed it should write
the arraylist in to the file. When the third button is pressed it should
read from the file in to an arraylist.
My problem is am getting only the first record , meaning if i enter 2
names , i only get the first name displayed when i press the third button.
Here is what i have done:
2 arraylists are decalred.
ArrayList<Person>list=new ArrayList<Person>()
ArrayList<Person>list2=new ArrayList<Person>();
The button which takes user input when pressed
String firstname=txtname.getText();
Person p1=new Person(firstname,"pamodya","15","08","1995");
list.add(p1);
The button which writes the first arraylist object in to the file. try{
FileOutputStream write=new FileOutputStream("hello.txt");
ObjectOutputStream writeFile=new ObjectOutputStream(write);
writeFile.writeObject(list);
writeFile.flush();
writeFile.close();
}catch(Exception e){e.getMessage();}
The button which reads from the file and prints to the text area when
pressed.
try{
FileInputStream read=new FileInputStream("hello.txt");
ObjectInputStream readFile=new ObjectInputStream(read);
Person p1=(Person)readFile.readObject();
list2.add(p1);
readFile.close();
txtarea.setText(p1.getName());
}catch(Exception e){e.getMessage();}
What seems to be the problem here? Thank you for your time.
No comments:
Post a Comment