I was studying Java Serialization for the first time which said that it could save the Object's 'state'.
So I tried to make a simple Java console game which would create a new 'player' and set its default IQ to 80. And whenever they ran the game (i.e. run the main function) they will find that their IQ has increased by 1 from the previous time.
Here is my code:
IQIncreaser.java
package IQIcreaserGame;
import java.io.Serializable;
public class IQIncreaser implements Serializable {
private int iq;
public int getIq() {
return iq;
}
public void setIq(int iq) {
this.iq = iq;
}
#Override
public String toString() {
return "Your IQ is now: " + iq;
}
}
Main.java
package IQIcreaserGame;
import java.io.*;
public class Main {
public static void main(String[] args) {
IQIncreaser bakra = new IQIncreaser();
bakra.setIq(80);
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:/saveIQ.ser"));
oos.writeObject(bakra);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Welcome to the IQ increaser!!!");
System.out.println("Whenver you run this game your IQ will increase by 1!!");
System.out.println("Just check it out");
System.out.println("Your IQ at beginning was " +bakra.getIq() + ", come back for more");
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:/saveIQ.ser"));
IQIncreaser restoredAndIncreased = (IQIncreaser) ois.readObject();
// Here I am increasing the IQ by one everytime the main runs
restoredAndIncreased.setIq(restoredAndIncreased.getIq()+1);
System.out.println("The increased IQ is " + restoredAndIncreased.getIq());
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now the problem/confusion part:
Whenever I run the game i.e. everytime I run main() function I thought I would get a expected output in which the player's IQ would increase by 1 because it takes the "previous value" from the .ser saved file and adds 1 to it.
Like this the first default value is 80
Then on second run : 81
then on third run: 82
then on fourth run: 83.. and so on
But everytime I am getting 81 as the increased value. Where is the problem and what is the best way to fix this?
Please find the complete code below. Basically you need to ensure that you are overwriting the file one it has been created, else, you are restoring the IQ back to 80.
Finally ensure your serialize your object back to same filw after incrementing the IQ.
class IQIncreaser implements Serializable{
int Iq ;
public int getIq() {
return Iq;
}
public void setIq(int iq) {
Iq = iq;
}
}
public class Main {
public static void main(String[] args) {
Path path = Paths.get("/home/akshayap/saveIQ.ser");
//create default file only if it does not exist
if (Files.notExists(path)) {
IQIncreaser bakra = new IQIncreaser();
bakra.setIq(80);
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/home/akshayap/saveIQ.ser"));
oos.writeObject(bakra);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("Welcome to the IQ increaser!!!");
System.out.println("Whenver you run this game your IQ will increase by 1!!");
System.out.println("Just check it out");
IQIncreaser restoredAndIncreased=null;
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/home/akshayap/saveIQ.ser"));
restoredAndIncreased = (IQIncreaser) ois.readObject();
System.out.println("Your IQ at beginning was " +restoredAndIncreased.getIq() + ", come back for more");
// Here I am increasing the IQ by one everytime the main runs
restoredAndIncreased.setIq(restoredAndIncreased.getIq()+1);
System.out.println("The increased IQ is " + restoredAndIncreased.getIq());
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
//serialize the object into the same file post increment
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/home/akshayap/saveIQ.ser"));
oos.writeObject(restoredAndIncreased);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
update bakra.setIq also
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:/saveIQ.ser"));
IQIncreaser restoredAndIncreased = (IQIncreaser) ois.readObject();
// Here I am increasing the IQ by one everytime the main runs
restoredAndIncreased.setIq(restoredAndIncreased.getIq()+1);
bakra.setIq(restoredAndIncreased.getIq()+1);
System.out.println("The increased IQ is " + restoredAndIncreased.getIq());
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
You initially run the writeObject() function and everytime it saves 80 as the value. But when you increment the value from the latter part of the code you don't write it to the file. Just increment, read and ignore.
Event though you write it there it will again replace to 80 because of following code in upper part of main method.
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:/saveIQ.ser"));
oos.writeObject(bakra);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
Solution
You have to initially set the value 80 and save it to file.
Then when ever you run the program just increment the value and save it again. Don't initialize it into 80 again.
public static void main(String[] args) {
IQIncreaser bakra = new IQIncreaser();
bakra.setIq(80);
try {
if (!Paths.get("D:/saveIQ.ser").toFile().exists()) {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/tmp/abc.ser"));
oos.writeObject(bakra);
oos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Welcome to the IQ increaser!!!");
System.out.println("Whenver you run this game your IQ will increase by 1!!");
System.out.println("Just check it out");
System.out.println("Your IQ at beginning was " + bakra.getIq() + ", come back for more");
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:/saveIQ.ser"));
IQIncreaser restoredAndIncreased = (IQIncreaser) ois.readObject();
// Here I am increasing the IQ by one everytime the main runs
restoredAndIncreased.setIq(restoredAndIncreased.getIq() + 1);
System.out.println("The increased IQ is " + restoredAndIncreased.getIq());
ois.close();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:/saveIQ.ser"));
oos.writeObject(restoredAndIncreased);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Related
I'm working on appending objects to a binary file. My professor has provided an "appendable" output stream class for us to use on this assignment, and from my understanding this is what should prevent a corrupted header. However, I'm still getting a corrupted header when I attempt to open the binary file. The name of the file is test.dat and as far as I can tell the program writes the data just fine, but as soon as I try reading from it everything goes out the window.
fileName is a data field in the same class these methods are defined in and is defined as follows File filename = new File("test.dat");
If anyone could point me in the right direction that would be fantastic! Thanks in advance
My Code
/**
Writes a pet record to the file
#param pets The pet record to write
*/
public static void writePets(PetRecord pet){
AppendObjectOutputStream handle = null;
try{
handle = new AppendObjectOutputStream(new FileOutputStream(fileName, true));
handle.writeObject(pet);
handle.flush();
} catch (IOException e){
System.out.println("Fatal Error!");
System.exit(0);
} finally {
try{
handle.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
/**
Reads all pets from the file so long as the user continues to enter "next"
*/
public static void readPets(){
Scanner keys = new Scanner(System.in);
String input = "";
ObjectInputStream handle = null;
PetRecord pet = null;
try{
handle = new ObjectInputStream(new FileInputStream(fileName)); // stack trace points here
do{
try{
pet = (PetRecord) handle.readObject();
System.out.println("\n" + pet);
System.out.println("[*] type \"next\" to continue");
input = keys.nextLine();
} catch (IOException e){
System.out.println("\t[*] No More Entries [*]");
e.printStackTrace();
break;
}
} while (input.matches("^n|^next"));
handle.close();
} catch (ClassNotFoundException e){
System.out.println("The dat file is currupted!");
} catch (IOException e){
System.out.println("\t[*] No Entries! [*]");
e.printStackTrace();
}
}
Provided class:
public class AppendObjectOutputStream extends ObjectOutputStream
{
// constructor
public AppendObjectOutputStream( OutputStream out ) throws IOException
{
// this constructor just calls the super (parent)
super(out);
}
#Override
protected void writeStreamHeader() throws IOException
{
// this forces Java to clear the previous header, re-write a new header,
// and prevents file corruption
reset();
}
}
Stack Track:
java.io.StreamCorruptedException: invalid stream header: 79737200
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:808)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:301)
at UIHandle.readPets(UIHandle.java:381)
at UIHandle.list(UIHandle.java:79)
at UIHandle.command(UIHandle.java:103)
at UIHandle.mainUI(UIHandle.java:40)
at UIHandle.main(UIHandle.java:405)
Turns out it helps if you make sure a file exits before appending to it.
The problem wasn't with reading the file, but attempting to append to a file when it wasn't there. The fix was a simple if/else to check to see if the file existed. If it doesn't exist then write the file as usual, if it does exist then use the custom append class.
/**
Writes a pet record to the file
#param pet The pet record to write
*/
public static void writePet(PetRecord pet){
if (fileName.exists()){
AppendObjectOutputStream handle = null;
try{
handle = new AppendObjectOutputStream(new FileOutputStream(fileName, true));
handle.writeObject(pet);
handle.flush();
} catch (IOException e){
System.out.println("Fatal Error!");
System.exit(0);
} finally {
try{
handle.close();
} catch (IOException e){
e.printStackTrace();
}
}
} else {
ObjectOutputStream handle = null;
try{
handle = new ObjectOutputStream(new FileOutputStream(fileName));
handle.writeObject(pet);
handle.flush();
} catch (IOException e){
System.out.println("Fatal Error!");
System.exit(0);
} finally {
try{
handle.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
I am performing a project, where so far in the discipline, we can not use database to persist the data. I am persisting the data in .tmp files. The first time I persisted the list of doctors, and it worked, but now that I'm trying to persist the patient user data, but this error happens, that file is not found.
These are my load, anda save methods in the class "SharedResources":
public void loadUserPatient(Context context) {
FileInputStream fis1;
try {
fis1 = context.openFileInput("patient.tmp");
ObjectInputStream ois = new
ObjectInputStream(fis1);
userPatient = (UserPatient) ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
public void saveUserPatient(Context context) {
FileOutputStream fos1;
try {
fos1 = context.openFileOutput("patient.tmp",
Context.MODE_PRIVATE);
ObjectOutputStream oos =
new ObjectOutputStream(fos1);
oos.writeObject(userPatient);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
here is the whole class: https://ideone.com/f3c74u
the error is happening on line 16 of MainActivity:
SharedResources.getInstance().loadUserPatient(this);
here is the whole class "Main": https://ideone.com/OyiljP
And I think this error is ocurring because of the 52nd line of the UserPatientAdd class:
SharedResources.getInstance().getUserPatient();
because when I work with an ArrayList, I put an add at the end of the line, like:SharedResources.getInstance().getDoctors().add(doctor);
And I get confused on how to proceed when I deal only with a user.
This is the whole UserPatientAdd class: https://ideone.com/clUSa3
How can I solve this problem?
You need to set the UserPatient using something like this
In your SharedResources class, create a new method:
public void setUserPatient(UserPatient user) {
userPatient = user;
}
Then in your UserPatientAdd class set the new object:
UserPatient userPatient = new UserPatient (birth, name, bloodType, bloodPressure, cbpm, vacinesTaken, vacinesToBeTaken,
allergies,weight, height, surgeries, desease);
SharedResources.getInstance().setUserPatient(userPatient);
Done
This question already has answers here:
Why are empty catch blocks a bad idea? [closed]
(20 answers)
Closed 5 years ago.
I have 3 very small classes.
The main class:
import java.io.*;
public class ConnectionManager {
public static void main(String argv[]) {
try {
PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pin = new PipedInputStream(pout);
Sender s = new Sender(pout, true);
Receiver r = new Receiver(pin, true);
System.out.println("Starting threads");
s.start();
r.start();
} catch (Exception e) {}
}
}
The Sender class
import java.io.*;
import java.util.Random;
public class Sender extends Thread {
ObjectOutputStream oos;
boolean primitive;
public Sender(OutputStream os, boolean primitive) {
try {
oos = new ObjectOutputStream(os);
} catch (Exception e) {}
this.primitive = primitive;
}
public void run() {
Random rand = new Random();
while (true) {
try {
System.out.println("Integer is being sent");
oos.writeInt(10);
Thread.sleep(1000);
} catch (Exception e) {}
}
}
}
And the Receiver class
import java.io.*;
public class Receiver extends Thread {
ObjectInputStream ois;
boolean primitive;
public Receiver(InputStream is, boolean primitive) {
try {
ois = new ObjectInputStream(is);
} catch (Exception e) {}
this.primitive = primitive;
}
public void run() {
System.out.println("Receiver is starting");
while (true) {
try {
int x = ois.readInt();
System.out.print("An int was read: " + x);
} catch (Exception e) {}
}
}
}
Please ignore seemingly unused variables like primitive and rand. They're holdovers from slightly different versions that I was testing out earlier and I was too lazy to remove them.
Anyway, when I run the main method in ConnectionManager, I get this as output:
Starting threads
Receiver is starting
Integer is being sent
Integer is being sent
Integer is being sent
Integer is being sent
Integer is being sent
Integer is being sent
Integer is being sent
Integer is being sent
//... ad infinitum
Why is the receiver thread not getting the messages that are piped through? What am I missing here?
In your code, there is an exception like java.io.IOException: Read end dead.
You are NOT able to spot because you are suppressing them with empty catch blocks.
The main point is that you need to change Sender and Receiver classes to use PipedOutputStream and PipedInputStream as shown below :
Sender class:
public class Sender extends Thread {
PipedOutputStream oos;
public Sender(PipedOutputStream os) {
try {
this.oos = os;
} catch (Exception e) {System.out.println(e);}
}
public void run() {
try {
System.out.println("Integer is being sent");
oos.write(10);
oos.close();
Thread.sleep(1000);
} catch (Exception e) {System.out.println(e);}
}
}
Receiver class:
public class Receiver extends Thread {
PipedInputStream ois;
public Receiver(PipedInputStream is) {
try {
this.ois = is;
} catch (Exception e) {System.out.println(e);}
}
public void run() {
System.out.println("Receiver is starting");
try {
int x = ois.read();
System.out.print("An int was read: " + x);
} catch (Exception e) {System.out.println(e);}
}
}
main() method:
public static void main(String[] args) throws Exception {
try {
PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pin = new PipedInputStream(pout);
Sender s = new Sender(pout);
Receiver r = new Receiver(pin);
System.out.println("Starting threads");
s.start();
r.start();
} catch (Exception e) {
System.out.println(e);
}
}
OUTPUT:
Starting threads
Receiver is starting
Integer is being sent
An int was read: 10
As a side note, remember that, empty catch blocks are very bad practice as they hide the exceptions, so I strongly suggest not to use them in the code.
I'm learning now how to do serialization using Java Language. I have read some posts and docs about the subject and I tried to do a simple example (below)
public class SterializeObject implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private transient int code;
public SterializeObject (String n, int c){
name = n;
code = c;
}
public void printAtributes (){
System.out.println("name: " + name + "; code: " + code);
}
}
public class MainClass {
public static void main(String[] agrs) {
SterializeObject ob1 = new SterializeObject("ana", 1);
SterializeObject ob2 = new SterializeObject("rita", 2);
try {
FileOutputStream fileOut = new FileOutputStream("file.data");
ObjectOutputStream outObj = new ObjectOutputStream(fileOut);
outObj.writeObject(ob1);
outObj.writeObject(ob2);
outObj.close();
System.out.println("Objects were serialized!");
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<SterializeObject> list = new ArrayList<SterializeObject>();
try {
FileInputStream fileInput = new FileInputStream("file.data");
ObjectInputStream inputObj = new ObjectInputStream(fileInput);
Object o;
try {
while ((o = inputObj.readObject()) != null) {
list.add((SterializeObject) o);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Erro foi aqui! (1)");
}
inputObj.close();
fileInput.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erro foi aqui! (2)");
}
for (int i = 0; i < list.size(); ++i) {
list.get(i).printAtributes();
}
}
}
I created a Class SterializeObject that implements java.io.Serializable with two variables: one string (name) and one int (code) that is transient. Then In the main I generate two instances of that class and I tried to write it in a file, that I have done successfully! After that, I try to read the two object with a Loop.. there is my problem.. since the ObjectInputStream dosen't have some kind of method to see if we are in the end or not. So, I tried to do with this condition: (o = inputObj.readObject()) != null.
My output is this:
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at MainClass.main(MainClass.java:30)
Objects were serialized!
Erro foi aqui! (2)
name: ana; code: 0
name: rita; code: 0
I get the objects, but I get an error because, I think, is trying to access to something that doesn't exist.
Someone can tell me other way to do it?
Best Regards.
Read as many objects as the number of written objects, or write the list of objects itself, instead of writing every object one after the other.
(Or rely on the EOFException to detect the end of the stream, but this is ugly).
As many of you told me to do, I created a ArrayList and serialized the ArrayList.
My code is:
public class MainClass {
public static void main(String[] agrs) {
SterializeObject ob1 = new SterializeObject("ana", 1);
SterializeObject ob2 = new SterializeObject("rita", 2);
ArrayList <SterializeObject> list = new ArrayList<>();
list.add(ob1);
list.add(ob2);
ArrayList <SterializeObject> input = new ArrayList<SterializeObject>();
try {
FileOutputStream fileOut = new FileOutputStream("file.data");
ObjectOutputStream outObj = new ObjectOutputStream(fileOut);
outObj.writeObject(list);
outObj.close();
System.out.println("Objects were serialized!");
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fileInput = new FileInputStream("file.data");
ObjectInputStream inputObj = new ObjectInputStream(fileInput);
Object o;
try {
input = (ArrayList<SterializeObject>) inputObj.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Erro foi aqui! (1)");
}
inputObj.close();
fileInput.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Erro foi aqui! (2)");
}
for (int i = 0; i < input.size(); ++i) {
input.get(i).printAtributes();
}
}
}
And the output is:
Objects were serialized!
name: ana; code: 0
name: rita; code: 0
Thank you for the help!
Close the FileOutputStream also along with ObjectOutputStream
fileOut.close();
Why don't you add both object to an ArrayList, and serialize the ArrayList. Then you just have to Deserialize the ArrayList and it will be populated with both objects.
You can do this by placing the readObject call inside a try-catch block and catching that EOFException you get, signaling you have read all the objects.
Replace your while loop with this piece of code
do{
try
{
o = inputObj.readObject();
list.add((SterializeObject) o);
}
catch(EOFException e)
{
o = null;
}
}while (o != null);
hello dear colleagues,
I have a Garden class in which I serialize and deserialize multiple Plant class objects. The serializing is working but the deserializing is not working if a want to assign it to calling variable in the mein static method.
public void searilizePlant(ArrayList<Plant> _plants) {
try {
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for (int i = 0; i < _plants.size(); i++) {
out.writeObject(_plants.get(i));
}
out.close();
fileOut.close();
} catch (IOException ex) {
}
}
deserializing code:
public ArrayList<Plant> desearilizePlant() {
ArrayList<Plant> plants = new ArrayList<Plant>();
Plant _plant = null;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
Object object = in.readObject();
// _plant = (Plant) object;
// TODO: ITERATE OVER THE WHOLE STREAM
while (object != null) {
plants.add((Plant) object);
object = in.readObject();
}
in.close();
} catch (IOException i) {
return null;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
return null;
}
return plants;
}
My invoking code:
ArrayList<Plant> plants = new ArrayList<Plant>();
plants.add(plant1);
Garden garden = new Garden();
garden.searilizePlant(plants);
// THIS IS THE PROBLEM HERE
ArrayList<Plant> dp = new ArrayList<Plant>();
dp = garden.desearilizePlant();
edit
I got a null Pointer exception
The solution of #NilsH is working fine, thanks!
How about serializing the entire list instead? There's no need to serialize each individual object in a list.
public void searilizePlant(ArrayList<Plant> _plants) {
try {
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(_plants);
out.close();
fileOut.close();
} catch (IOException ex) {
}
}
public List<Plant> deserializePlant() {
List<Plants> plants = null;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
plants = in.readObject();
in.close();
}
catch(Exception e) {}
return plants;
}
If that does not solve your problem, please post more details about your error.
It may not always be feasible to deserialize a whole list of objects (e.g., due to memory issues). In that case try:
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
filename));
while (true) {
try {
MyObject o = (MyObject) in.readObject();
// Do something with the object
} catch (EOFException e) {
break;
}
}
in.close();
Or using the Java SE 7 try-with-resources statement:
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(
filename))) {
while (true) {
MyObject o = (MyObject) in.readObject();
// Do something with the object
}
} catch (EOFException e) {
return;
}
If you serialize it to an array linear list, you can cast it back to an array linear list when deserializing it -- all other methods failed for me:
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
public class Program
{
public static void writeToFile(String fileName, Object obj, Boolean appendToFile) throws Exception
{
FileOutputStream fs = null;
ObjectOutputStream os = null;
try
{
fs = new FileOutputStream(fileName);
os = new ObjectOutputStream(fs);
//ObjectOutputStream.writeObject(object) inherently writes binary
os.writeObject(obj); //this does not use .toString() & if you did, the read in would fail
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
os.close();
fs.close();
}
catch(Exception e)
{
//if this fails, it's probably open, so just do nothing
}
}
}
#SuppressWarnings("unchecked")
public static ArrayList<Person> readFromFile(String fileName)
{
FileInputStream fi = null;
ObjectInputStream os = null;
ArrayList<Person> peopleList = null;
try
{
fi = new FileInputStream(fileName);
os = new ObjectInputStream(fi);
peopleList = ((ArrayList<Person>)os.readObject());
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch(EOFException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
os.close();
fi.close();
}
catch(Exception e)
{
//if this fails, it's probably open, so just do nothing
}
}
return peopleList;
}
public static void main(String[] args)
{
Person[] people = { new Person(1, 39, "Coleson"), new Person(2, 37, "May") };
ArrayList<Person> peopleList = new ArrayList<Person>(Arrays.asList(people));
System.out.println("Trying to write serializable object array: ");
for(Person p : people)
{
System.out.println(p);
}
System.out.println(" to binary file");
try
{
//writeToFile("output.bin", people, false); //serializes to file either way
writeToFile("output.bin", peopleList, false); //but only successfully read back in using single cast
} // peopleList = (ArrayList<Person>)os.readObject();
// Person[] people = (Person[])os.readObject(); did not work
// trying to read one at a time did not work either (not even the 1st object)
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("\r\n");
System.out.println("Trying to read object from file. ");
ArrayList<Person> foundPeople = null;
try
{
foundPeople = readFromFile("input.bin");
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if (foundPeople == null)
{
System.out.println("got null, hummm...");
}
else
{
System.out.println("found: ");
for(int i = 0; i < foundPeople.size(); i++)
{
System.out.println(foundPeople.get(i));
}
//System.out.println(foundPeople); //implicitly calls .toString()
}
}
}