简体   繁体   English

如何在vert.x中泵送具有偏移量和长度的流?

[英]How to pump streams with offset and length in vert.x?

I'm porting a kotlin rest server to Vert.x, but I have some trouble finding an alternative to InputStream.skip() , OutputStream.write(buffer, 0, len) and how to append to a file on disk. 我正在将Kotlin Rest服务器移植到Vert.x,但是在查找InputStream.skip()OutputStream.write(buffer, 0, len)的替代方案以及如何附加到磁盘上的文件时遇到了一些麻烦。

Is it possible using the Pump.pump() ? 可以使用Pump.pump()吗? Do I have to override the ReadStream and WriteStream ? 我必须重写ReadStreamWriteStream吗?

My old code is: 我的旧代码是:

    val fromOffset = FROM_OFFSET.getLongParam(req, false, 0)
    val toOffset = TO_OFFSET.getLongParam(req, false, -1)

    val component = repository.getComponent(contRep, docId, compId)

    component.inputStream.use { input ->
        res.outputStream.use { output ->
            input.skip(fromOffset)
            val buffer = ByteArray(64 * 1024)
            var len: Int
            var read = 0
            do {
                len = input.read(buffer)

                // Check offset
                read += len
                if (toOffset in 0..(read - 1))
                    len -= (read - toOffset).toInt()

                if (len > 0) output.write(buffer, 0, len)

            } while (len > 0)
        }
    }

And, to append to a file: 并且,附加到文件:

    inputStream.use { appendStream ->
        FileOutputStream(componentFile, true).use { outputStream ->
            appendStream.copyTo(outputStream)
        }
    }

Thanks in advance 提前致谢

You can open a file in append mode. 您可以在追加模式下打开文件。 Then when you call write the buffer goes to the end of the file: 然后,当您调用write ,缓冲区将转到文件末尾:

vertx.fileSystem().open(fileName, new OpenOptions().setAppend(true), ar -> {
  if (ar.succeeded()) {
    AsyncFile writestream = ar.result();
    // If you write here it will be at the end of the file
  }
});

For skipping, just use AsyncFile#setReadPos : 要跳过,只需使用AsyncFile#setReadPos

vertx.fileSystem().open(fileToRead, new OpenOptions(), ar -> {
  if (ar.succeeded()) {
    AsyncFile readstream = ar.result();
    rs.setReadPos(offset);
  }
}

When this is done you can use the usual pump code: 完成后,您可以使用通常的泵代码:

Pump pump = Pump.pump(readstream, writestream);
readstream.endHandler(v -> {
  // Done
});
pump.start();

These are all Java snippets but you'll easily convert to Kotlin syntax. 这些都是Java代码段,但是您可以轻松转换为Kotlin语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM