read method
Reads some number of bytes from the input stream and stores them into
the buffer array b
.
The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.
If the length of b
is zero, then no bytes are read and 0
is returned;
otherwise, there is an attempt to read at least one byte. If no byte is
available because the stream is at the end of the file, the value -1
is returned; otherwise, at least one byte is read and stored into b
.
Parameters
b
: The buffer into which the data is readoffset
: The start offset in arrayb
at which the data is writtenlength
: The maximum number of bytes to read
Returns
The total number of bytes read into the buffer, or -1
if there is no
more data because the end of the stream has been reached.
Example
final input = FileInputStream('data.bin');
final buffer = Uint8List(1024);
// Read up to 1024 bytes
final bytesRead = await input.read(buffer);
if (bytesRead != -1) {
print('Read $bytesRead bytes');
processData(buffer.sublist(0, bytesRead));
}
// Read into a specific portion of the buffer
final partialRead = await input.read(buffer, 100, 500);
await input.close();
Throws InvalidArgumentException if offset
or length
is negative, or if
offset
+ length
is greater than the length of b
.
Throws IOException if an I/O error occurs.
Throws StreamClosedException if the stream has been closed.
Implementation
@override
Future<int> read(List<int> b, [int offset = 0, int? length]) async {
checkClosed();
length ??= b.length - offset;
if (offset < 0 || length < 0 || offset + length > b.length) {
throw InvalidArgumentException('Invalid offset or length');
}
if (length == 0) {
return 0;
}
int totalRead = 0;
// First, read from buffer if available
if (_position < _count) {
final availableInBuffer = _count - _position;
final toReadFromBuffer = length.clamp(0, availableInBuffer);
b.setRange(offset, offset + toReadFromBuffer, _buffer, _position);
_position += toReadFromBuffer;
totalRead += toReadFromBuffer;
offset += toReadFromBuffer;
length -= toReadFromBuffer;
}
// If we need more data and the request is large, read directly
if (length > 0 && length >= _buffer.length) {
final directRead = await _input.read(b, offset, length);
if (directRead > 0) {
totalRead += directRead;
} else if (totalRead == 0) {
return -1; // End of stream
}
} else if (length > 0) {
// Fill buffer and read from it
await _fillBuffer();
if (_count > 0) {
final toRead = length.clamp(0, _count);
b.setRange(offset, offset + toRead, _buffer, 0);
_position = toRead;
totalRead += toRead;
} else if (totalRead == 0) {
return -1; // End of stream
}
}
return totalRead;
}