本地文件中的RandomAccessFile.read()是否保证将读取确切的字节数? [英] Does RandomAccessFile.read() from local file guarantee that exact number of bytes will be read?

查看:437
本文介绍了本地文件中的RandomAccessFile.read()是否保证将读取确切的字节数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前我的代码工作正常,但是我应该在其中将 raf.read()替换为 raf.readFully()为了确保将读取所有字节?

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);

我的建议如下-从本地资源中读取文件一 read ()调用将始终返回指定的字节数。 readFully 在从网络流中读取时非常有用,当 read()不保证将读取所需的字节数时。

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?

推荐答案

read 方法不能保证读取所有请求的字节(即使它们存在于文件中)。实际行为将取决于基础操作系统和文件系统。例如,在有NFS支持的情况下,您更有可能在单个调用中无法获得所有请求的字节。

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.

如果您想保证获得所有请求的字节单个调用中的字节数,则必须使用 readFully

If you want to guarantee to get all the requested bytes in a single call, you must use readFully.

这篇关于本地文件中的RandomAccessFile.read()是否保证将读取确切的字节数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆