readFully method
Reads exactly length
bytes from the input stream.
This method repeatedly calls read until exactly length
bytes have
been read or the end of stream is reached. If the end of stream is
reached before length
bytes are read, an EndOfStreamException is thrown.
Parameters
length
: The exact number of bytes to read
Returns
A Uint8List containing exactly length
bytes.
Example
final input = FileInputStream('data.bin');
try {
// Read exactly 1024 bytes
final data = await input.readFully(1024);
print('Read exactly ${data.length} bytes');
processData(data);
} catch (EndOfStreamException e) {
print('File was shorter than expected');
} finally {
await input.close();
}
Throws EndOfStreamException if the end of stream is reached before
length
bytes are read.
Throws IOException if an I/O error occurs.
Throws StreamClosedException if the stream has been closed.
Implementation
Future<Uint8List> readFully(int length) async {
checkClosed();
final buffer = Uint8List(length);
int totalRead = 0;
while (totalRead < length) {
final bytesRead = await read(buffer, totalRead, length - totalRead);
if (bytesRead == -1) {
throw EndOfStreamException('Expected $length bytes but only $totalRead available');
}
totalRead += bytesRead;
}
return buffer;
}