readAll method

Future<Uint8List> readAll()

Reads all remaining bytes from the input stream.

This method reads from the current position until the end of the stream is reached. The returned list contains all the bytes that were read.

Returns

A Uint8List containing all remaining bytes in the stream.

Example

final input = FileInputStream('small_file.txt');
try {
  final allData = await input.readAll();
  print('Read ${allData.length} bytes total');
  final text = String.fromCharCodes(allData);
  print('Content: $text');
} finally {
  await input.close();
}

Throws IOException if an I/O error occurs. Throws StreamClosedException if the stream has been closed.

Implementation

Future<Uint8List> readAll() async {
  checkClosed();

  final chunks = <List<int>>[];
  final buffer = Uint8List(8192); // 8KB buffer
  int totalLength = 0;

  int bytesRead;
  while ((bytesRead = await read(buffer)) != -1) {
    chunks.add(Uint8List.fromList(buffer.sublist(0, bytesRead)));
    totalLength += bytesRead;
  }

  // Combine all chunks into a single array
  final result = Uint8List(totalLength);
  int offset = 0;
  for (final chunk in chunks) {
    result.setRange(offset, offset + chunk.length, chunk);
    offset += chunk.length;
  }

  return result;
}