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

隐身守侯 提交于 2019-12-13 19:35:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!