Home > Blockchain >  Read a socket direclty from InputStream or from BufferedReader?
Read a socket direclty from InputStream or from BufferedReader?

Time:03-08

My goal is to read the n number of bytes from a Socket.

Is it better to directly read from the InputStream, or wrap it into a BufferedReader?

Throughout the net you find both approaches, but none states which to use when.

Socket socket;
is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));

char[] buffer = new char[CONTENT_LENGTH];

//what is better?
is.read(buffer);
br.read(buffer);

CodePudding user response:

An InputStream is byte-oriented. A Reader is character-oriented.

Since readers are for reading characters, they are better when you are dealing with input that is of a textual nature (or data represented as characters). I say better because Readers (in the context of typical usage) are essentially streams with methods that easily facilitate reading character input.

Source

You may refer Java Docs for Reader and InputStream, and read other answers here

CodePudding user response:

Since your goal is to "read the n number of bytes" there is little point creating a character Reader from your input as this might mean the nth byte is part way into a character - and assuming that the stream is character based.

Since JDK11 there is handy call for reading n bytes:

byte[] input = is.readNBytes(n);

If n is small or you repeat above often, consider reading the stream using one of bis = new BufferedInputStream(is), in.transferTo(out) or len = read(byteArray) which may be be more effective for longer streams.

  • Related