Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading file line by line in dart

Tags:

dart

dart-io

I'm trying to process large text files in a language Dart. The files have a size over 100 MB.

I tried readAsLines and readAsLinesSync methods of dart:io library. Every time I run out of memory: Exhausted heap space.

Is there a way to read a file line by line or byte by byte as in other languages​​?

like image 941
Martin Janda Avatar asked Feb 16 '14 15:02

Martin Janda


People also ask

How do you read line by line darts?

To read File as a String in Dart, you can use File. readAsString() method or File. readAsStringSync().

Which stream is suitable for reading File in Dart?

When reading or writing a file, you can use streams (with openRead), random access operations (with open), or convenience methods such as readAsString, Most methods in this class occur in synchronous and asynchronous pairs, for example, readAsString and readAsStringSync.


2 Answers

This should read the file in chunks:

import 'dart:async';
import 'dart:io';
import 'dart:convert';

main() {
  var path = ...;
  new File(path)
    .openRead()
    .map(utf8.decode)
    .transform(new LineSplitter())
    .forEach((l) => print('line: $l'));
}

There isn't much documentation about this yet. Perhaps file a bug asking for more docs.

like image 171
Greg Lowe Avatar answered Oct 19 '22 15:10

Greg Lowe


In the latest verion of dart the UTF8.decoder is now utf8.decoder:

import 'dart:async';
import 'dart:io';
import 'dart:convert';

main() {
  var path = ...;
  new File(path)
    .openRead()
    .transform(utf8.decoder)
    .transform(new LineSplitter())
    .forEach((l) => print('line: $l'));
}
like image 8
Brett Sutton Avatar answered Oct 19 '22 16:10

Brett Sutton