read method
Reads characters into an array.
This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.
Parameters
cbuf
: Destination bufferoffset
: Offset at which to start storing characters (default: 0)length
: Maximum number of characters to read (default: remaining buffer space)
Returns
The number of characters read, or -1 if the end of the stream has been reached.
Example
final reader = FileReader('text.txt');
try {
final buffer = List<int>.filled(1024, 0);
final charsRead = await reader.read(buffer);
if (charsRead != -1) {
final text = String.fromCharCodes(buffer.sublist(0, charsRead));
print('Read: $text');
}
} finally {
await reader.close();
}
Throws InvalidArgumentException if offset
or length
is negative, or if
offset
+ length
is greater than the length of cbuf
.
Throws IOException if an I/O error occurs.
Throws StreamClosedException if the reader has been closed.
Implementation
Future<int> read(List<int> cbuf, [int offset = 0, int? length]) async {
checkClosed();
length ??= cbuf.length - offset;
if (offset < 0 || length < 0 || offset + length > cbuf.length) {
throw InvalidArgumentException('Invalid offset or length');
}
if (length == 0) {
return 0;
}
final firstChar = await readChar();
if (firstChar == -1) {
return -1;
}
cbuf[offset] = firstChar;
int charsRead = 1;
try {
for (int i = 1; i < length; i++) {
final char = await readChar();
if (char == -1) {
break;
}
cbuf[offset + i] = char;
charsRead++;
}
} catch (e) {
// Return what we've read so far
}
return charsRead;
}