I am going through the oracle API for java.io.RandomAccessFile class.
There’s method called read() in the class which reads byte of data from the file passed to the constructor:-
public int read()
throws IOExceptionReads a byte of data from this file. The byte is returned as an
integer in the range 0 to 255 (0x00-0x0ff). This method blocks if no
input is yet available.Although RandomAccessFile is not a subclass of InputStream, this
method behaves in exactly the same way as the InputStream.read()
method of InputStream.Returns:
the next byte of data, or -1 if the end of the file has been reached. Throws:
IOException – if an I/O error occurs. Not thrown if end-of-file has been reached.
I am confused, does it mean to say that it reads 8 bits of data from the file passed to the constructor and convert the read contents to int.
Any suggestions?
What is confusing you, exactly?
Yes, it reads one byte of data, which is 8 bits, and returns it as an integer value in the inclusive range 0..255. So if the file in question happens to be a text file, and the first character is a capital ‘A’,
read()will return 65.It returns an
intinstead of abyteso that it can return the full range 0..255 as a positive number, and still have -1 available as a sentinel value for end-of-file (though arguably an exception would have been a better way to do that).