readLine method

  1. @override
Future<String?> readLine()
override

Reads a line of text.

A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Returns

A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached.

Example

final reader = FileReader('lines.txt');
try {
  String? line;
  int lineNumber = 1;
  while ((line = await reader.readLine()) != null) {
    print('Line $lineNumber: $line');
    lineNumber++;
  }
} finally {
  await reader.close();
}

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

Implementation

@override
Future<String?> readLine() async {
  await _ensureOpen();

  if (_buffer == null || _bufferPosition >= _buffer!.length) {
    return null; // End of file
  }

  final startPosition = _bufferPosition;
  int endPosition = startPosition;

  // Find the end of the line
  while (endPosition < _buffer!.length) {
    final char = _buffer!.codeUnitAt(endPosition);
    if (char == 10) { // '\n'
      break;
    } else if (char == 13) { // '\r'
      // Check for '\r\n'
      if (endPosition + 1 < _buffer!.length &&
          _buffer!.codeUnitAt(endPosition + 1) == 10) {
        endPosition++; // Skip the '\n' as well
      }
      break;
    }
    endPosition++;
  }

  final line = _buffer!.substring(startPosition, endPosition);

  // Move past the line terminator
  if (endPosition < _buffer!.length) {
    _bufferPosition = endPosition + 1;
  } else {
    _bufferPosition = endPosition;
  }

  return line;
}