Question

I am looking for a Java DataOutputStream equivalent for Dart where I can write arbitrary types (int, string, float, byte array etc). There is RandomAccessFile but it does not provide byte array or float-double values. ByteArray seems to have some necessary functions but I am not sure how to write it to a file or an OutputStream.

Was it helpful?

Solution

Here is some simple code showing how to write a ByteArray into an OutputStream:

#import('dart:io');
#import('dart:scalarlist');

main() {
        File file = new File("c:\\temp\\foo.txt");
        OutputStream os = file.openOutputStream();
        os.onNoPendingWrites = () {
                print('Finished writing. Closing.');
                os.flush();
                os.close();
        };
        Uint8List byteList = new Uint8List(64);
        ByteArray byteArray = byteList.asByteArray();
        int offset = 0;
        offset = byteArray.setUint8(offset, 72);
        offset = byteArray.setUint8(offset, 101);
        offset = byteArray.setUint8(offset, 108);
        offset = byteArray.setUint8(offset, 108);
        offset = byteArray.setUint8(offset, 111);
        offset = byteArray.setUint8(offset, 0);
        byteArray.setFloat32(offset, 1.0);
        os.write(byteList);
}

OTHER TIPS

You are essentially asking for arbitrary object serialization. And while the Dart VM has one, it isn't exposed to programmers (it is only used for snapshotting and message passing). I'd say that it would be a mistake to expose it -- in different situations, we have different requirements for serialization and "one true solution" isn't gonna work (Java showed us that already).

For example, I'm working on a MsgPack implementation for Dart, I know that Protobuf port is also in the works, maybe someone will start a Thrift port... the possibilities are endless.

The closest thing I could find is this package: https://github.com/TomCaserta/dart_io/ . Unfortunately there is a bug when reading to the end of the byte array - see my pull request in GitHub.

You could use this class: https://github.com/TomCaserta/dart_io/blob/master/lib/data_output.dart

Unfortunately (a) it doesn't handle streams; (b) writeLong doesn't take a single integer. I have raised an issue for the Dart SDK: https://github.com/dart-lang/sdk/issues/31166

Edit: I have forked the dart_io package and fixed the two problems described above. My new package is published as dart_data_io: https://github.com/markmclaren2/dart_data_io

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top