Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt on ObjectStreams

 
Anand Damodaran
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

why do i get null message in the following code?

Output:
Student{name=anand, age=25}
Student{name=damodaran, age=20}
null



Kindly help me...

with respect,
Anand
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The way you invoke readObject() is guaranteed to throw an EOFException:
ObjectInputStream Javadoc wrote:
Any attempt to read object data which exceeds the boundaries of the custom data written by the corresponding writeObject method will cause an OptionalDataException to be thrown with an eof field value of true. Non-object reads which exceed the end of the allotted data will reflect the end of data in the same way that they would indicate the end of the stream: bytewise reads will return -1 as the byte read or number of bytes read, and primitive reads will throw EOFExceptions.

My bet is that the the getMessage() call in your catch block returns null. Try adding ex.printStackTrace(); to the catch block to find out.
 
Anand Damodaran
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jelle Klap wrote:The way you invoke readObject() is guaranteed to throw an EOFException:
ObjectInputStream Javadoc wrote:
Any attempt to read object data which exceeds the boundaries of the custom data written by the corresponding writeObject method will cause an OptionalDataException to be thrown with an eof field value of true. Non-object reads which exceed the end of the allotted data will reflect the end of data in the same way that they would indicate the end of the stream: bytewise reads will return -1 as the byte read or number of bytes read, and primitive reads will throw EOFExceptions.

My bet is that the the getMessage() call in your catch block returns null. Try adding ex.printStackTrace(); to the catch block to find out.



Hi,

Can you alter the code to read the exact two object without any exception?


Kindly help me..


Regards,
Anand
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sure, you could simply make two successive invocations of the readObject() method, instead of looping. The same way you invoke writeObject().
By the way, don't forget to properly close your streams! As of Java 7 the easiest way would be to use the try-with-resources approach.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic