Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vert.x Write Buffer to WriteStream?

Tags:

vert.x

At a Vert.x verticle I'm implementing I have a Buffer that was previously loaded into memory and now I want to dump it into disk.

As far as I understood we should use a Pump to make sure not to overload the WriteStream.

But I'm not finding a way to get a ReadStream child instance from a Buffer. Shouldn't there be an easy / standard way to do this?

Regards

like image 268
João Rebelo Avatar asked May 10 '26 03:05

João Rebelo


1 Answers

Generally, vert.x does not warn on any issues writing directly into AsyncFiles. Furthermore, they provide the corresponding example of using AsyncFile.write directly here and state that you can use those to write directly: http://vertx.io/docs/vertx-core/java/#_asynchronous_files

However, if you want the pump with Buffer you need an instance of ReadStream<Buffer> along with an AsyncFile to pump into. You can make use of the implementation by PitchPoint Solutions (Copyright 2016 The Simple File Server Authors):

https://github.com/pitchpoint-solutions/sfs/blob/master/sfs-server/src/main/java/org/sfs/io/BufferReadStream.java

Putting it all together:

CompletableFuture<Void> done = new CompletableFuture<>();

Buffer buffer = Buffer.buffer(new byte[100]);

Vertx.vertx().fileSystem.open("myfile.txt", new OpenOptions(), res -> {
    if (res.succeeded()) {
        AsyncFile outputFile = res.result();

        BufferReadStream reader = new BufferReadStream(buffer)
        Pump pump = Pump.pump(reader, outputFile);
        pump.start();
        reader.endHandler((r) -> {
            pump.stop(); // not sure this is required
            done.complete(null);
        });

    } else {
        // Something went wrong!
    }
});

// wait elsewhere
done.get();
like image 193
Oleg Sklyar Avatar answered May 15 '26 21:05

Oleg Sklyar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!