Is it mandatory to implement Serializable class when serializing a class .I tried to put object data into file with and without serializable implementation and found absolutely no difference.
snippet -1
import java.io.*;
import java.net.*;
public class SerializableTest {
int a= 10;
String test="Serialize test";
public static void main(String [] args){
SerializableTest test =new SerializableTest();
test.save();
}
public void save(){
try{
FileOutputStream fs = new FileOutputStream("save.res");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(test);
os.close();
}
catch (Exception ex ){
System.out.println("Error in opening or saving file");
}
System.out.println("Complete");
}
}
snippet -2
import java.io.*;
import java.net.*;
public class SerializableTest **implements Serializable**{
int a= 10;
String test="Serialize test";
public static void main(String [] args){
SerializableTest test =new SerializableTest();
test.save();
}
public void save(){
try{
FileOutputStream fs = new FileOutputStream("save.res");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(test);
os.close();
}
catch (Exception ex ){
System.out.println("Error in opening or saving file");
}
System.out.println("Complete");
}
}
In both cases program ran fine and contents of save.res looked absolutely similar.
What is the advantage of implementing Serializable when I can do things without implementing.
Serializable should ideally be implemented by the object that needs to be serialized. String implements Serializable. You are serializing a String object. You are not serializing SerializableTest.
In other words, it does not matter if SerializableTest implements Serializable or not since SerializableTest is not the object that is being serialized.
Related
I have a program in which I am trying to implement saving and loading of obejcts, however I couldn't get the loading to work after the program closes, so effectively only saving and loading works while the program is open, but no data is ever loaded once the program starts. I assume this is something to do with overwiting. I created a test program to see if I could get it to work just using a simple Person class. I store my Peson objects inside an ArrayList and serialize it, then deserialize it. Currently I am storing all loaded Person objects in a JComboBox. I have looked online and could not find anything that will help. Also note I am aware that using serialization is not the best method of saving objects, but it's something suitable to use for my program.
My App Class:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
public class App extends JFrame {
public static JComboBox<Person> peopleBox;
public App(){
try {
Person.peopleList = loadList();
}
catch(IOException | ClassNotFoundException e){
System.out.println(e.getMessage());
}
try {
saveList(Person.peopleList);
}catch (IOException e){
System.out.println(e.getMessage());
}
peopleBox = new JComboBox<>();
peopleBox.setModel(getComboBoxModel(Person.peopleList));
add(peopleBox);
pack();
setSize(600, 400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public DefaultComboBoxModel<Person> getComboBoxModel(ArrayList<Person> peopleList){
Person[] comboBoxModel = peopleList.toArray(new Person[0]);
return new DefaultComboBoxModel<>(comboBoxModel);
}
public static void saveList(ArrayList<Person> peopleList) throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("test.bin"));
objectOutputStream.writeObject(peopleList);
}
public static ArrayList<Person> loadList() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("test.bin"));
Person.peopleList = (ArrayList<Person>) objectInputStream.readObject();
return Person.peopleList;
}
public static void main(String[] args){
// Person p = new Person("Sean", 22);
try {
saveList(Person.peopleList);
}catch (IOException e){
System.out.println(e.getMessage());
}
App app = new App();
app.pack();
app.setVisible(true);
}
}
Person Class
import java.io.Serializable;
import java.util.ArrayList;
public class Person implements Serializable {
public int age;
public String name;
public static ArrayList<Person> peopleList = new ArrayList<>();
public Person(String name, int age){
this.age = age;
this.name = name;
peopleList.add(this);
for(Person p : peopleList){
System.out.println(p.toString());
}
}
public Person(){
}
public String toString(){
return "Name : " + name + " Age: " + age;
}
}
I expect when I save the list to the "test.bin" file, close the program, then open it again that it will load the list and display the Objects I created before I closed the program. I appreciate any help, thanks.
You are saving an empty list before you load Person from the file.
I suggest this approach:
import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class App extends JFrame {
public static JComboBox<Person> peopleBox;
public App() {
try {
loadList();
} catch (IOException | ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
saveList(Person.peopleList);
} catch (IOException e) {
System.out.println(e.getMessage());
}
setSize(600, 400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void updateData(){
peopleBox = new JComboBox<>();
peopleBox.setModel(getComboBoxModel(Person.peopleList));
add(peopleBox);
pack();
}
public DefaultComboBoxModel<Person> getComboBoxModel(ArrayList<Person> peopleList) {
Person[] comboBoxModel = peopleList.toArray(new Person[0]);
return new DefaultComboBoxModel<>(comboBoxModel);
}
public static void saveList(ArrayList<Person> peopleList) throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("test.bin"));
objectOutputStream.writeObject(peopleList);
}
public static void loadList() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("test.bin"));
Person.peopleList.addAll((List<Person>) objectInputStream.readObject());
}
public static void main(String[] args) {
App app = new App();
Person p = new Person("Sean2", 24);
try {
saveList(Person.peopleList);
} catch (IOException e) {
System.out.println(e.getMessage());
}
app.updateData();
app.setVisible(true);
}
}
my research on google-search and stackoverflow regarding this problem didn't resolve it.
i'd like to show you a snipped of my Datastructure:
there's a class, called "SequenceHolder" => this one carries an:
ArrayList<SequenceData> data;
within the Sequenceholder, there is a function to call the serialization:
public void writeSequenceList() throws FileNotFoundException, IOException {
FileOutputStream fout = new FileOutputStream(path);
ObjectOutputStream oout = new ObjectOutputStream(fout);
oout.writeObject(data);
oout.close();
fout.close();
}
The class SequenceObject has following fields: (this one is on the top, where i start the serialization)
private ArrayList<SequenceModel> recordedSequenceData;
private String sequenceUrl;
while the SequenceModel is defined like this:
private Object sequenceRawData;
private boolean isProcessedByRequest;
The sequenceRawdata objects are basically two other classes (containing Strings only)!
every class of this "trail" implements the interface "Serializable".
this is the deserialization:
public ArrayList<SequenceData> loadSequenceList() throws FileNotFoundException, IOException, ClassNotFoundException {
FileInputStream fileIn = new FileInputStream(path);
ObjectInputStream in = new ObjectInputStream(fileIn);
this.data = (ArrayList<SequenceData>) in.readObject();
in.close();
fileIn.close();
return data; // load from de-serialization
}
after a deserialization of the SequenceObject, i'll only retrieve the "sequenceUrl", but no recordedSequenceData.
Is there a trick to do this?!
It came just up to my mind, to extend some classes with the ObjectOutputStream and call the writingprocess with "this" explicitly in every class - but yeah, i am not sure if thats a good idead.
What do you mean by "The sequenceRawdata objects are basically two other classes (containing Strings only)!" because when I try to run the same program :
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
class SequenceModel implements Serializable
{
public SequenceModel(Object a, boolean b)
{
sequenceRawData = a;
isProcessedByRequest = b;
}
public String toString()
{
return (String)sequenceRawData + isProcessedByRequest + " SeqModel ";
}
private Object sequenceRawData;
private boolean isProcessedByRequest;
}
class SequenceData implements Serializable
{
public SequenceData(ArrayList<SequenceModel> a, String b)
{
recordedSequenceData = a;
sequenceUrl = b;
}
public String toString()
{
return recordedSequenceData + sequenceUrl + " SeqData ";
}
private ArrayList<SequenceModel> recordedSequenceData;
private String sequenceUrl;
}
class SequenceHolder implements Serializable
{
ArrayList<SequenceData> data;
public String toString()
{
return data + " SeqHol ";
}
public SequenceHolder(ArrayList<SequenceData> a)
{
data = a;
}
public void writeSequenceList() throws FileNotFoundException, IOException {
FileOutputStream fout = new FileOutputStream(Test.file);
ObjectOutputStream oout = new ObjectOutputStream(fout);
oout.writeObject(data);
oout.close();
fout.close();
}
public ArrayList<SequenceData> loadSequenceList() throws FileNotFoundException, IOException, ClassNotFoundException {
FileInputStream fileIn = new FileInputStream(Test.file);
ObjectInputStream in = new ObjectInputStream(fileIn);
this.data = (ArrayList<SequenceData>) in.readObject();
in.close();
fileIn.close();
return data; // load from de-serialization
}
}
public class Test
{
public static File file = new File("abc.txt");
public static void main(String[] args)
{
SequenceModel obj = new SequenceModel("abc", false);
ArrayList list = new ArrayList(); list.add(obj);
SequenceData obh = new SequenceData(list, "str");
ArrayList l2 = new ArrayList();
l2.add(obh);
SequenceHolder obi = new SequenceHolder(l2);
try {
obi.writeSequenceList();
System.out.println(obi.loadSequenceList());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
it is able to serialize and deserialize both and there is no problem.
Output it is printing is : [[abcfalse SeqModel ]str SeqData ] which includes everything as desired.
Please let me know if I am missing anything.
package example;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.Object;
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
public class mytest {
public static void main(String[] args) throws IOException {
clone
}
}
For above code, it wants to show the deep copy of Java. But myeclipse reports some errors. But I don't know what is wrong with it?
Could anyone please help to point them out?
Changed the code according to your suggestion.
package example;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.Object;
class Utils {
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
}
public class mytest {
public static void main(String[] args) throws IOException {
Object clonedObject = Utils.copy(new Object());
clonedObject.notifyAll();
}
}
Further:
Thank you all!
I modifeid the code like above, it becomes better but still cannot run normally.
The new error message is below:
Any new suggestion?
You can't have floating methods in Java. Everything must be a member of a class. In this instance, a dummy class with only static methods called Utils would be common practice.
e.g.
public class Utils {
// Static methods go here
public static Object copy(Object oldObj) {
// etc
}
}
Then you can call it like so:
public class mytest {
public static void main(String[] args) throws IOException {
Object clonedObject = Utils.copy(new Object());
// etc
}
}
Here are the following steps to solve your errors:
Make a package inside a Project(Specific Name)
Inside a created package make a name MyTest.
Write or copy the method into that class which has been created
above.
To Run the Program Make one main Method any call it by there name if
it is static.
If your method is not static make a object of the class and call by
that object of the class.
It will solve your Error & also run your program...
Note: Try to put finally block to free the resources like object, ByteArrayOutputStream & ObjectStream etc.... It will increase your performance of the program.
You need to put a method into a class.
public class SomeClass{
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
And you can use it as:
public class mytest {
public static void main(String[] args) throws IOException {
Object object = Someclass.copy(someObject);
}
}
You can't declare methods (even static ones) outside of a class in Java. You would have to put everything (except the imports) inside a class.
You'll need something like:
public class YourClass {
public static Object copy(Object oldObj) {
...
}
}
The method public static Object copy(Object oldObj) isn't located in a class. That's why you are getting the error.
You must add a class named mytest as the 'top level scope' of this file, nest all other methods in it.
class mytest {
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
public class mytest {
public static void main(String[] args) throws IOException {
clone
}
}
}
As a side note, you should rename the class name (and file name) to MyTest and MyTest.java - to match the java coding convention.
You should put your method in a class, preferably called mytest since it's the name of the file, declared like
public class mytest {
//Your method here
}
Also note that the naming convention in Java is to have class names starting with a capital letter, so it would be MyTest, and your file should be renamed to reflect that.
Try
public class MyTest {
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
public static void main(String[] args) throws IOException {
clone
}
}
There are no methods who do not belong to a class (like a JavaScript-Function).
Static means that the method does belong to the class and not to an instance of the class as a non static method would do
You can't write methods outside the class. Put your method #copy inside the class. like this:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class mytest
{
public static void main(String[] args) throws IOException
{
// Now you can use your method here
}
public static Object copy(Object oldObj)
{
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
}
Where is the class here? these method should contain a class.
Your java class should looks like this
package name;
imports;
public class MyClass{
public void myMethod(){
}
}
Trying to compilie this AuctionClientMain.java and this is the error I get and can't figur it out:
AuctionClientMain.java:16: cannot access AuctionClient
bad class file: .\AuctionClient.class
class file contains wrong class: Assignment.AuctionClient
Please remove or make sure it appears in the correct subdirectory of the classpath.
AuctionClient a = new AuctionClient(args[0],args[1],port);
I have included AuctionClientMain.java
import Auction.*;
import java.io.*;
public class AuctionClientMain
{
//Create the client
public static void main (String args[]) throws IOException
{
if(args.length!=3)
{
throw new RuntimeException ("Syntax: java AuctionClient <name> <serverhost> <port>");
}
//Convert port taken in as string to an integer
int port = Integer.parseInt(args[2]);
AuctionClient a = new AuctionClient(args[0],args[1],port);
}
}
And the Auction Client
package Auction;
import java.io.*;
import java.net.*;
public class AuctionClient
{
public AuctionGui gui;
private Socket socket;
private DataInputStream dataIn;
private DataOutputStream dataOut;
//Auction Client constructor String name used as identifier for each client to allow server to pick the winning bidder
public AuctionClient(String name,String server, int port)
{
//Create a new gui
gui = new AuctionGui("Bidomatic 5000");
//Add the key listener to the input field
gui.input.addKeyListener (new EnterListener(this,gui));
//Add the exit listener to the window
gui.addWindowListener(new ExitListener(this));
try
{
//Create a new socket with server name and port number provided
socket = new Socket(server, port);
//Create new data input stream
dataIn = new DataInputStream(socket.getInputStream());
//Create new data outpit stream
dataOut = new DataOutputStream(socket.getOutputStream());
dataOut.writeUTF(name);
while (true)
{
gui.output.append("\n"+dataIn.readUTF());
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
//Send bid to output stream
public void sentBid(String bid)
{
try
{
//Write bid out
dataOut.writeUTF(bid);
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void disconnect()
{
try
{
socket.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Your AuctionClientMain class seems to be in the default package. The AuctionClient class is in package Auction. The .class file for AuctionClient needs to be in a subdirectory named Auction relative to AuctionClientMain.
Alternatively, put AuctionClient in the default package or put AuctionClientMain in package Auction.
On a side note, Java conventions are that package names are all lower case. It would be better to use package auction; instead of package Auction;.
Because AuctionClient is in the Auction pacakge, the compiler expects to find the Java source file in a directroy called Auction.
I have a list of around 20,000 object, which in turn have a very huge hierarchy. I need to dump the objects into a file, so that i can read it later anytime during my process. Now my problem is, I have worked on Java but not that much on serialization and i dont have that much of knowledge how to do that.
In this case as far as i know, i need to use both Serialization ane De-Serialization. Can anyone please help. Also i can use any new API or normal Java Serialization.
Regards.
Look at this link http://www.java2s.com/Code/Java/File-Input-Output/Objectserialization.htm
Its something like this:
Card3 card = new Card3(12, Card3.SPADES);
System.out.println("Card to write is: " + card);
try {
FileOutputStream out = new FileOutputStream("card.out");
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(card);
oos.flush();
} catch (Exception e) {
System.out.println("Problem serializing: " + e);
}
Card3 acard = null;
try {
FileInputStream in = new FileInputStream("card.out");
ObjectInputStream ois = new ObjectInputStream(in);
acard = (Card3) (ois.readObject());
} catch (Exception e) {
System.out.println("Problem serializing: " + e);
}
System.out.println("Card read is: " + acard);
Don't forget to implement Serializable interface in all class you want to save
and put modifier "transient" at all fields you don't want to save.
(e.g. private transient List cache;)
Rather than saving every object individually you can directly save the list of objects. I am using below code to achieve this. Although I am serializing for cloning, it should be sufficient to learn the basics.
public static List<EmpoyeeTO> deepCloneList( List<EmpoyeeTO> objectList) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(objectList);
oos.flush();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
return (List<EmpoyeeTO>) ois.readObject();
}catch(EOFException eof){
return objectList;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
JSON is all the rage recently so you can use that. Jackson is a nice api for JSON serialization/deserialization. As a bonus you get interoperability with other platforms.
If you're not affraid of xml use JAXB
Of course you can always use binary serialization, but IMO text is easier to manage than blobs.
below is the code to write objects to file using XMLEncoder, assuming that your object implements Serializable Interface.
FileOutputStream os =new FileOutputStream("c:/temp/serialized.xml");
XMLEncoder encoder=new XMLEncoder(os);
encoder.writeObject(objectToBeSerialized);
encoder.close();
Below is the code to deserializ the Data
FileInputStream is=new FileInputStream("c:/temp/serialized.xml");
XMLDecoder decoder=new XMLDecoder(is);
Object object=(Object)decoder.readObject();
decoder.close();
I give you a sample
import java.io.Serializable;
public class Account implements Serializable {
private int accountNo;
private String custName;
private int balance;
/** Creates a new instance of Account */
public Account(int accNo, String name, int bal) {
this.accountNo = accNo;
this.custName = name;
this.balance = bal;
}
#Override
public String toString() {
String str = "Account No:" + this.accountNo;
str += "\nCustomer name:" + this.custName;
str += "\nBalance:" + this.balance;
return str;
}
}
Write and read object
package me.dev;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public void writeObject(ArrayList<Object> listAccount) throws IOException {
//Create FileOutputStream to write file
FileOutputStream fos = new FileOutputStream("C:\\bank.datum");
//Create ObjectOutputStream to write object
ObjectOutputStream objOutputStream = new ObjectOutputStream(fos);
//Write object to file
for (Object obj : listAccount) {
objOutputStream.writeObject(obj);
objOutputStream.reset();
}
objOutputStream.close();
}
public ArrayList<Account> readObject() throws ClassNotFoundException, IOException {
ArrayList<Account> listAccount = new ArrayList();
//Create new FileInputStream object to read file
FileInputStream fis = new FileInputStream("C:\\bank.datum");
//Create new ObjectInputStream object to read object from file
ObjectInputStream obj = new ObjectInputStream(fis);
try {
while (fis.available() != -1) {
//Read object from file
Account acc = (Account) obj.readObject();
listAccount.add(acc);
}
} catch (EOFException ex) {
//ex.printStackTrace();
}
return listAccount;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws ClassNotFoundException {
try {
// TODO code application logic here
ArrayList<Object> listAcc = new ArrayList<Object>();
listAcc.add(new Account(1, "John", 1000));
listAcc.add(new Account(2, "Smith", 2000));
listAcc.add(new Account(3, "Tom", 3000));
Main main = new Main();
main.writeObject(listAcc);
ArrayList<Account> listAccount = main.readObject();
System.out.println("listisze:" + listAccount.size());
if (listAccount.size() > 0) {
for (Account account : listAccount) {
System.out.println(((Account) account).toString());
}
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}