java.io.FileInputStream, ,有一个方法 int read(Byte[] buffer,int offset,int numBytes);我们如何使用这个函数 - 这个方法和 read(byte[] buffer)?

有帮助吗?

解决方案

正如Javadoc中指出(以及参数的名称表示),该方法具有偏移和的numBytes仅使用缓冲液的一部分,以把它的输出英寸

public int read(byte[] b,
            int off,
            int len)
     throws IOException

Parameters:
    b - the buffer into which the data is read.
    off - the start offset of the data.
    len - the maximum number of bytes read. 

如果你想重用已经在有数据已有的缓冲区,你不想要揍(当然,从numBytes开始offset会被覆盖),您可以使用此方法。

在Java中,几乎所有的缓冲区操作提供这种接口。使用恰当,就可以避免复制/缓冲数据的次数超过必要的。

其他提示

刚刚从 javadoc 得到这个。

从此输入流中读取最多 len 个字节的数据到字节数组中。如果 len 不为零,则该方法将阻塞,直到某些输入可用为止;否则,不会读取任何字节并返回 0。

参数:

  • b - 读取数据的缓冲区。
  • off - 目标数组 b 中的起始偏移量
  • len - 读取的最大字节数。

返回:读入缓冲区的总字节数,如果由于已到达文件末尾而没有更多数据,则为 -1。

http://java.sun.com/javase/6/docs/api/java/io/FileInputStream.html#read(byte[], ,整数,整数)

此功能是非常有用的读取整个文件到存储器中。看到这个例子中,

File = new File("/anywhere/anyfile");
InputStream is = new FileInputStream(file);
long fileSize = file.length();
byte[] bytes = new byte[(int)fileSize];
int offset = 0;
int count=0; 
while (offset < fileSize) {
    count=is.read(bytes, offset, fileSize-offset));
    if (count >= 0)
        offset += count;
    else
        throw new IOException("Can't read file "+file.getName());
}
is.close();
// Now bytes has all the complete file. 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top