0

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);
membersound
  • 81,582
  • 193
  • 585
  • 1,120

1 Answers1

1

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 and you repeat the above often, consider reading the stream using one of bis = new BufferedInputStream(is), in.transferTo(out) or len = read(byteArray) which may be more effective for longer streams.

DuncG
  • 12,137
  • 2
  • 21
  • 33
  • In my opinion "there is little point" is euphemism for "you should/can not". There is almost zero chance that reading bytes through a Reader is the good abstraction, even though it may work : it is undefined why or when it would, which is pretty much not what you expect from software at any point. In that sense, I find the expression polite, but almost misleading, I would be more assertive about it. – GPI Mar 08 '22 at 14:31