File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please help me debug this - Converting Object to byte[] and vice versa.

 
Sreenivasan Padmanabhan
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone tell me what is the problem here. When I convert an Object into byte[] and then convert it back to an object, I dont get the proper output.
This is the output I get:
107
[B@f276af2

Thanks,
Sreenivasan

import java.io.*;

public class temp
{
public static void main(String args[])
{
help obj = new help();
obj.a = 10;
obj.b = 'a';
System.out.println(obj.a + obj.b);
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
byte[] b = new byte[bos.size()];
b = bos.toByteArray();

final ByteArrayInputStream ios = new ByteArrayInputStream(b);
ObjectInputStream os = new ObjectInputStream(ios);
Object x;
help x1 = new help();
x = os.readObject();
x1 = (help)x;
System.out.print(x1.a + x1.b);
}catch (Exception e) {
// ignore
}
System.out.println(new byte[0]);
}
}

class help
{
public int a;
public char b;
}
 
Ulf Dittmer
Rancher
Pie
Posts: 42966
73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch. A couple of comments:


bos.close();
byte[] b = new byte[bos.size()];
b = bos.toByteArray();

I wouldn't do anything with a stream after it's closed (although it doesn't matter here, because the array 'b' is never used). You can also shorten that to

because there's no need to create the array first - the toByteArray method does that.

Object x;
help x1 = new help();
x = os.readObject();
x1 = (help)x;

This can be written shorter as

or even

No need to instantiate a new 'help' object first.

}catch (Exception e) {
// ignore
}

You should not ignore an exception, especially in code like this where you're not sure if or how it's working. At least print out the message that goes with it -e.getMessage()- so that you know an exception occurred.

System.out.println(new byte[0]);

I'm not sure what good printing out a freshly allocated array might do?

Overall, I'm guessing that an exception does actually occur, which leads to the second System.out.println statement never being executed.
[ April 12, 2007: Message edited by: Ulf Dittmer ]
 
Sreenivasan Padmanabhan
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks on your tips!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic