Search code examples
javabufferrandomaccessfile

Does RandomAccessFile.read() from local file guarantee that exact number of bytes will be read?


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?


Solution

  • 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.