ilomambo
ilomambo

Reputation: 8350

Android Inputread stream reads exactly the given buffer size?

I am reading a file with:

char [] buffer = new char[300];
FileInputStream istream = new FileInputStream(path);
InputStreamReader file = new InputStreamReader(istream);
size = file.read(buffer);
file.close();

After a few tries, it turns out that the file.read(buffer) reads exactly the number of chars allocated for buffer (in this case, 300, even that the file has much more characers in it).

Can I rely on read() always reading as much as it can, without generating any exception?
Or is this an undocumented feature?

The read method description says:

Reads characters from this reader and stores them in the character array buf starting at offset 0. Returns the number of characters actually read or -1 if the end of the reader has been reached.

There is no mention of the buffer allocation issue. This is very important, and a good thing that it works this way, because it allows you to define the size of the buffer as you want/need and there is no need to guess, no need to code for exceptions. Actually, it is read(char[] buffer) but it works as read(char[] buffer, int size).

Upvotes: 0

Views: 578

Answers (1)

Houf
Houf

Reputation: 597

Yes you can rely on this call, unless an I/O error occurs, which is already mentionned in the api.

If you look at the code of read(char cbuf[]) you'll notice it calls the method public int read (char[] buffer, int offset, int length).

From Android source code:

public int read(char cbuf[]) throws IOException { read(cbuf, 0, cbuf.length);}

In your implementation, you need to continue reading the file with file.read(buffer) to obtain remaining bytes. The content of buffer needs to be appended to another buffer that will grow, depending on the size of the file you're reading.

You could also allocate that buffer with the size of the file with the method getTotalSpace()

Upvotes: 1

Related Questions