java - Read from InputStream exact length -
i’m implementing program in java downloads web pages using http protocol. after sending get
request server , reading response headers (incl. content-length
) program reads char
array amount of chars (as specified in content-length
).
i’ve tried using both bufferedreader
, inputstreamreader
classes.
the problem
if content-length
high enough, part of stream read , rest of bytes not touched (like end has read available bytes , other end hadn’t finished writing).
the reason
as stated in documentation of bufferedreader
class:
this iterated
read
continues until 1 of following conditions becomes true: *specified number of characters have been read read
method of underlying stream returns *-1
, indicating end-of-file, or * *ready
method of underlying stream * returnsfalse
, indicating further input requests * block.
i’m afraid bullet number 3 causing read
quit in middle although amount of bytes specified not yet read.
i can implement functionality myself, wondering if there’s class ignores bullet number 3 , blocks until bytes have been read, not find one.
try (bufferedreader buffer = new bufferedreader(new inputstreamreader(stream))) { char[] arr = new char[contentlength]; buffer.read(arr, 0, contentlength); text.append(arr); }
the meaning of part ready()
method of underlying reader
block until @ least 1 character has been transferred, not block again. there no guarantee fill buffer.
you have loop.
Comments
Post a Comment