Converting EmailMessage to ByteArrayOutputStream

2019-07-19 16:39发布

问题:

I am fetching email from Exchange server using Java EWS API (EWS - Exchange Web Services) and storing it in a proprietary CMS. The type in which I am getting message is microsoft.exchange.webservices.data.EmailMessage - a class provided by EWS API. The CMS API requires ByteArrayOutputStream object as a parameter to its method.

So I want to convert EmailMessage object to ByteArrayOutputStream. I saw this thread and tried similar like this: (Below item is of type EmailMessage)

ByteArrayOutputStream b = new ByteArrayOutputStream();
try
{
    ObjectOutputStream o  = new ObjectOutputStream(b);
    o.writeObject((Object)item);
}
catch(IOException ioe)   
{
    ioe.printStackTrace(); 
}

But I am getting

java.io.NotSerializableException: microsoft.exchange.webservices.data.EmailMessage
     at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180)   
     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)

I am able to save these EmailMessage objects in .eml format using FileOutputStream, however now I am not able to find the way to convert them to ByteArrayOutputStream. So is there any way to convert FileOutputStream to ByteArrayOutputStream or just directly from EmailMessage to ByteArrayOutputStream.

回答1:

You are getting this exception because your (Object)item's class not implementing Serializable interface. From java doc writeObject(Object obj)

Exceptions are thrown for problems with the OutputStream and for classes that should not be serialized. All exceptions are fatal to the OutputStream, which is left in an indeterminate state, and it is up to the caller to ignore or recover the stream state.