public static byte[] objectToByteArray(Object obj) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objOut = null;
try {
objOut = new ObjectOutputStream(out);
objOut.writeObject(obj);
objOut.flush();
} finally {
objOut.close();
out.close();
}
return out.toByteArray();
}
Main Method :
public static void main(String[] args) throws IOException {
//
// System.out.println(getFileName("/home/local/ZOHOCORP/bharathi-1397/logs/bharathi-1397.csez.zohocorpin.com_2012_05_24.log",0));
try {
throw new IOException("Error in main method");
} catch (IOException io) {
System.out.println(new String(objectToByteArray(io.getMessage()),
"UTF-8"));
}
//
}
Output :
��
I want to convert Object to byte[] but why it returns ctrl characters like this . I didn’t understand can you please help me .
Serialization converts an object into binary data. It’s fundamentally not text data – just like an image file isn’t text data.
Your code tries to interpret this opaque binary data as if it were UTF-8-encoded text data. It’s not, so no wonder you’re seeing garbage. If you opened up an image file in a text editor, you’d see similar non-useful text. You can try to interpret the data as text (as you are doing) but you won’t get anything useful out.
If you want to represent opaque binary data as text in a printable, reversible manner you should use base64 or hex. There are lots of libraries available to convert to base64, including this public domain one.