How to read a file line by line in Dart

前端 未结 4 843
深忆病人
深忆病人 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条回答
  •  Happy的楠姐
    2021-01-19 17:49

    Because none of the other answers suited my situation, here is another technique:

    import 'dart:io';
    import 'dart:convert';
    
    
    void main()
    {
        var file = File('/path/to/some/file.txt);
        var raf = file.openSync(mode: fileMode.read);
    
        String line;
        while ((line = readLine(raf)) != null)
        {
            print(line);
        }
      }
    
      String readLine(RandomAccessFile raf, {String lineDelimiter = '\n'}) {
    
        var line = '';
        int byte;
        var priorChar = '';
    
        var foundDelimiter = false;
    
        while ((byte = raf.readByteSync()) != -1) {
          var char = utf8.decode([byte]);
    
          if (isLineDelimiter(priorChar, char, lineDelimiter)) {
            foundDelimiter = true;
            break;
          }
    
          line += char;
          priorChar = char;
        }
        if (line.isEmpty && foundDelimiter == false) {
          line = null;
        }
        return line;
      }
    
    
      bool isLineDelimiter(String priorChar, String char, String lineDelimiter) {
        if (lineDelimiter.length == 1) {
          return char == lineDelimiter;
        } else {
          return priorChar + char == lineDelimiter;
        }
      }
    

提交回复
热议问题