Nicolas François
Nicolas François

Reputation: 777

Best practice reading file as InputStream

In Dart, I want to read BMP, so could be BIG file. I do it like this :

var inputStream = imageFile.openInputStream();
inputStream.onData = () {
  print(inputStream.available());
  inputStream.read(18); // Some headers
  int width = _readInt(inputStream.read(4));
  int height = _readInt(inputStream.read(4));
  // Another stuff ...
}

It works well with little image but when I a read a 3Mo file, the onData is executed many times. Indeed, the onData is trigged by 65536 bytes packets. What the best practice ? Should I write a automat with state like HEADER_STATE, COLORS_STATES, ... to set what is my reading state and consider by inputStream.read is a buffer ? Or I miss a reader class ? I fear to miss some bytes between 2 packets. I'm a little disappointed about this, when I do it in java, I just write :

inputStream.read(numberOfBytes);

More easy to use.

Upvotes: 1

Views: 1224

Answers (1)

Cutch
Cutch

Reputation: 3575

Once you have your RandomAccessFile open, you can do something like this:

RandomAccessFile raf; // Initialized elsewhere

int bufferSize = 1024*1024; // 1 MB
int offsetIntoFile = 0;
Uint8List byteBuffer = new Uint8List(bufferSize); // 1 MB
Future<int> bytesReadFuture = raf.readList(byteBuffer, offsetIntoFile, bufferSize);

bytesReadFuture.then((bytesRead) {
    Do something with byteBuffer here.
});

There is also a synchronous call readListSync.

John

Upvotes: 2

Related Questions