How to read a file line by line in Dart

前端 未结 4 840
深忆病人
深忆病人 2021-01-19 16:50

This question is a continuation of a previous question. I wrote the following piece of code to determine if File.openRead() created a Stream that could be stre

4条回答
  •  既然无缘
    2021-01-19 17:45

    I think this code is useful:

    import 'dart:io';
    import 'dart:convert';
    import 'dart:async';
    
    main() {
      final file = new File('file.txt');
      Stream> inputStream = file.openRead();
    
      inputStream
        .transform(utf8.decoder)       // Decode bytes to UTF-8.
        .transform(new LineSplitter()) // Convert stream to individual lines.
        .listen((String line) {        // Process results.
            print('$line: ${line.length} bytes');
          },
          onDone: () { print('File is now closed.'); },
          onError: (e) { print(e.toString()); });
    }
    

提交回复
热议问题