Skip to content
Advertisement

Read a socket direclty from InputStream or from BufferedReader?

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);

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement