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)
?
views:
879answers:
4As 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.
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)
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.