Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Serialization  RSS feed

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please see the following code snippet. It is throwing an exception in the second try and catch block and prints Deserialization failed. It is however not throwing exception in the first try and catch block. Please reply as soon as you can.
============================================================================


import java.io.*;

public class Save
{

public static void main(String args[])
{

Car a = new Car(45,"Ford");
Car b = new Car(30,"Skyon");

System.out.println (" The cost of a = "+ a.cost);

try
{
ObjectOutputStream os = new ObjectOutputStream( new FileOutputStream("Amey.ser") );
os.writeObject(a);
os.writeObject(b);

System.out.println (" The file is serialized");

os.close();

}

catch(IOException e){System.out.println (" Serialization failed");}

a=null;
b=null;

try
{

FileInputStream fis = new FileInputStream("Amey.ser");
ObjectInputStream is = new ObjectInputStream( fis );
Car a2= (Car) is.readObject();
Car b2= (Car) is.readObject();

System.out.println (" The cost of a after removing it from suspended animation = "+ a.cost);
}

catch( Exception ex) {System.out.println (" Deseriliazation failed");}





}

}
 
Ranch Hand
Posts: 242
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First and foremost thing to do is never swallow the exceptions in the catch blocks. Either propagate the exception or print it to log/screen.

Your code is failing due to a NullPointerException in and not due to de-serialization.

If you had printed the Exception like



you would have known about the problem and would have saved some time to post a question
 
Amey Rane
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HEY,

I am sorry for that mistake , should have caught it. Sorry, have just started learning intermediate Java.

Thank you for correcting me

Amey
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!