Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read x bytes from a stream?

I want to read exactly n bytes from a Socket at a time. How can I achieve that?

like image 492
Glenn Avatar asked Nov 03 '11 21:11

Glenn


People also ask

Which stream reads 2 bytes at a time?

Java provides many character stream classes, but the most common ones are- FileReader- It is used to read two bytes at a time from the source. The following is the constructor to create an instance of the FileReader class. FileReader in = new FileReader("filename");

What does Inputstream read return?

read. Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255 . If no byte is available because the end of the stream has been reached, the value -1 is returned.


1 Answers

DataInputStream.readFully() throws an exception on EOF, as Mark Peters points out. But there are two other methods who don't: Commons IO's IOUtils.read() and Guavas ByteStreams.read(). These both try to read up to N bytes, stopping only at EOF, and return how many they actually read.

like image 67
Alexander Torstling Avatar answered Oct 22 '22 20:10

Alexander Torstling