问题
Currently my code works fine but should I replace raf.read()
to raf.readFully()
in order to ensure that all bytes will be read?
raf = new RandomAccessFile(doc.getFilePath()+"/"+doc.getName(),"r");
raf.seek((partNumber-1)*partitionSize);
byte[] buf = new byte[partitionSize];
int bytesRead = raf.read(buf); //ensure myself by readFully or not?
System.out.println("expected="+partitionSize+" readed="+bytesRead);
My suggestion is the following - when reading from local resource like file one read()
call anyway will return specified number of bytes. readFully
useful when reading from network stream, when read()
does not guarantee that needed bytes count will be read. Is it correct?
回答1:
The read
method does not guarantee to read all requested bytes (even if they exist in the file). The actual behavior is going to be dependent on the underlying OS and file system. For example, when backed by NFS, you may be more likely to not get all the requested bytes in a single call.
If you want to guarantee to get all the requested bytes in a single call, you must use readFully
.
回答2:
As it is in documentation for RandomAccessFile#read(byte[] b)
Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of this file has been reached.
来源:https://stackoverflow.com/questions/28831729/does-randomaccessfile-read-from-local-file-guarantee-that-exact-number-of-byte