JavaSheriff
JavaSheriff

Reputation: 7665

Passing input stream around?

I am reading email attachments with javax.mail
I want to be able to pass the attachments from one class to the other
I am reading the attachment as part.getInputStream();

and other classes use Input stream as input
I am debating should create

AttachmentClass
    inputStream

Or

AttachmentClass
    byte[]

I know that passing InputStream might cause leaks and point to other objects not yours, while byte array will be the actual object.

The first option will be very simple:

AttachmentClass.setAttachment( part.getInputStream())
NextClass.doSomething(AttachmentClass)
NextClass.doSomething(AttachmentClass)

the second option will require conversion from InputStream to byte and vice-versa multiple times

AttachmentClass.setAttachment(convertToByte(part.getInputStream()))
NextClass.doSomething(ConvertToInputStream(AttachmentClass))
NextClass.doSomething(ConvertToInputStream(AttachmentClass))

what is the correct way to pass InputStream around?

Upvotes: 0

Views: 1577

Answers (1)

Prajjwal Srivastav
Prajjwal Srivastav

Reputation: 392

The first option is fine as long as you remember to close the InputStream in NextClass. The conversion in the second option is moot as you convert the InputStream object to byte array, only to convert it back to InputStream while calling it from the second class. If you can process the attachment in it's byte array form in NextClass, then the second option is worth it.

Upvotes: 1

Related Questions