dcsimg
java.io.IOException: Attempted read on closed stream
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   A_JP
Posted On:   Tuesday, July 13, 2004 05:37 PM

Iam trying to unmarshall (Castor based) an (xml) inputstream into a java object. There are two possible xml streams that I can expect, both falling under different schema. One is the successful xml and the other is the error xml. At first, Iam trying to unmarshall to the Sucess object (assuming it a success). If the xml stream is the error, then this marshalling would throw an MarshalException. While catching the MarshalException, Iam trying to unmarshal to the Error object, where it's failing with the following error : java.io.IOException: Attempted read on closed stream. I know the reason. Since I've already marshalled the stream, the file pointer is in the EOF. And when I try to unmarshal for the error condition, it say's the st   More>>

Iam trying to unmarshall (Castor based) an (xml) inputstream into a java object. There are two possible xml streams that I can expect, both falling under different schema. One is the successful xml and the other is the error xml.

At first, Iam trying to unmarshall to the Sucess object (assuming it a success). If the xml stream is the error, then this marshalling would throw an MarshalException. While catching the MarshalException, Iam trying to unmarshal to the Error object, where it's failing with the following error :
java.io.IOException: Attempted read on closed stream.

I know the reason. Since I've already marshalled the stream, the file pointer is in the EOF. And when I try to unmarshal for the error condition, it say's the stream is already closed.

Is there anyway, to position the pointer to the BOF or any other mechanism to read the stream bytes again ???

Thanks
Arun

   <<Less

Re: java.io.IOException: Attempted read on closed stream

Posted By:   Stephen_Ostermiller  
Posted On:   Wednesday, July 14, 2004 06:18 AM

If you need to read data from a stream more than once, you need to buffer the entire data. Depending on the size of the dataset you can either do this in memory or to the file system.


I'd recommend reading the entire stream to byte array and then create a ByteArrayInputStream on it to pass to your consumer. If you then have another consumer, you can create a new ByteArrayInputStream on that byte array.


To create a byte array, I'd recommend a ByteArrayOutputStream that you write to.



// Capture the data into memomory
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int read;
while((read=in.read(buffer))!=-1){
baos.write(buffer,0,read);
}
// Send the bytes to two different consumers
InputStream in1 = new ByteArrayInputStream(baos.toByteArray());
InputStream in2 = new ByteArrayInputStream(baos.toByteArray());
About | Sitemap | Contact