I want to read exactly n bytes from a Socket at a time. How can I achieve that?
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");
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With