You should use readFully
try (RandomAccessFile raf = new RandomAccessFile("filename", "r")) {
byte[] document = new byte[(int) raf.length()];
raf.readFully(document);
}
Edit: you've clarified your question. You want to know why read
does not "return" the contents of the file. How do the contents get there?
The answer is that read
does not allocate any memory to store the contents of the file. You did that with new byte[length]
. This is the memory where the file contents will go. You then call read
and tell it to store the contents of the file in this array of bytes you have created.
BufferedReader.readLine
does not operate like this because only it knows how many bytes need to be read for each line, so it does not make sense to get you to allocate them yourself.
Quick example of the "how":
class Test {
public static void main(String args[]) {
// here is where chars will be stored. If printed now, will show random junk
char[] buffer = new char[5];
// call our method. It does not "return" data.
// It puts data into an array we already created.
putCharsInMyBuffer(buffer);
// prints "hello", even though hello was never "returned"
System.out.println(buffer);
}
static void putCharsInMyBuffer(char[] buffer) {
buffer[0] = 'h';
buffer[1] = 'e';
buffer[2] = 'l';
buffer[3] = 'l';
buffer[4] = 'o';
}
}