简体   繁体   中英

Why PDF InputStream.read() returns -1?

I am getting a PDF document from a SOAP response and storing it in a file (even though I don't use it).

InputStream in = ( ( InputStream ) att.getContent() );

// TODO For now save in the file system
OutputStream outputStream = new FileOutputStream( "Sample.pdf" );

int read = 0;
byte[] bytes = new byte[1024];

// Write the data to the pdf file created
while((read=in.read(bytes))!=-1)
{
    outputStream.write( bytes, 0, read );
}
outputStream.flush();
outputStream.close();

return in;

I return in directly without closing the connection to another function:

DataOutputStream dataStream = new DataOutputStream(submitConnection.getOutputStream()); 

int read;
byte[] buffer = new byte[1024];
while((read = documentInputStream.read(buffer)) != -1) {
    dataStream.write(buffer, 0 , read);
}

dataStream.flush();
dataStream.close();
documentInputStream.close();

But when I tried this documentInputStream.read(buffer) returns -1 so I'm sending empty buffer to the connection submitConnection

PS: I debugged and when this happens documentInputStream has count = size of my Sample.pdf file so I assume this is correct.

Why can't I read the input stream again and send it to another output stream?

The doc says:

Returns: the next byte of data, or -1 if the end of the stream is reached.

means that you've already met the end of the stream, so there nothing more to read in this stream... Either reopen it or rewind it.

You can read a stream only once, as the data falls out of it as you read it.

SOME streams you can rewind to read them again, but streams coming in over a network are not usually of that nature.

What you'd need to do instead is buffer the content somewhere, maybe on a disk file, and then process it from there. This also minimises the time you need to keep your network connection open, often a good thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM