views:

879

answers:

4

In java.io.FileInputStream, there is a method int read(Byte[] buffer,int offset,int numBytes); how we can use this function - is there any difference between this method and read(byte[] buffer)?

+7  A: 

As the Javadoc points out (and the names of the parameters indicate), the method with offset and numBytes uses only part of the buffer to put its output in.

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.

You can use this method if you want to reuse an existing buffer that already has data in it that you do not want to clobber (Of course, the numBytes starting from offset will get overwritten).

In Java, almost all operations on buffers offer this kind of interface. Used properly, you can avoid copying/buffering data more times than necessary.

Thilo
That's especially interesting if you use a buffer for concurrently buffering and processing data from a stream. For instance a decoder for some media-format may read data from a stream into a buffer and another thread takes values from this buffer to process them. As the buffer may be filled before with some values you want to start refilling at a given offset (and therefore using the second parameter). If you filled the buffer completely, you will start from the beginning, but only using the space already processed by the other thread and use the len-param to achieve this.
Mnementh
+1  A: 

Just got this from the javadoc.

Reads up to len bytes of data from this input stream into an array of bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned.

Parameters:

  • b - the buffer into which the data is read.
  • off - the start offset in the destination array b
  • len - the maximum number of bytes read.

Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.

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

Nir Levy
A: 

This function is very useful to read a whole file into memory. See this example,

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.
ZZ Coder