readByte method

  1. @override
Future<int> readByte()
override

Reads the next byte of data from the input stream.

The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.

This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

Returns

The next byte of data, or -1 if the end of the stream is reached.

Example

final input = FileInputStream('data.txt');
int byte;
while ((byte = await input.readByte()) != -1) {
  print('Read byte: $byte');
}
await input.close();

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

Implementation

@override
Future<int> readByte() async {
  checkClosed();

  if (_bufferOffset < _buffer.length) {
    return _buffer[_bufferOffset++];
  }

  if (_isDone) {
    return -1; // End of stream
  }

  // Buffer is empty, wait for more data
  _readCompleter = Completer<void>();
  await _readCompleter!.future;

  if (_bufferOffset < _buffer.length) {
    return _buffer[_bufferOffset++];
  }

  if (_isDone) {
    return -1; // End of stream after waiting
  }

  // This case should ideally not be reached if _isDone is handled correctly
  // and data is always provided or stream is done.
  throw IOException('Failed to read byte: no data available after waiting.');
}