Netty: How to handle received chunks from a ChunkedFile

爱⌒轻易说出口 提交于 2019-12-06 06:09:45

Use a FileChannel:

ByteBuf in = ...;
ByteBuffer nioBuffer = in.nioBuffer();
FileOutputStream fos = new FileOutputStream("c:\\test.txt");
FileChannel channel = fos.getChannel();
while (nioBuffer.hasRemaining()) {
    channel.write(nioBuffer);
}
channel.close();
fos.close();

I use netty 4.1 version to receive chunks and write to file.

  1. use ByteBuf to receive the ChunkFile or FileRegion and convert it to ByteBuffer which is java nio.
  2. Get the FileChannel of RandomAccessFile and write ByteBuffer in.

Below is my handler code:

public class FileClientHandler extends ChannelInboundHandlerAdapter {

@Override
protected void channelRead(ChannelHandlerContext ctx, Object msg)
        throws Exception {

    File file = new File(dest);//remember to change dest

    if (!file.exists()) {
        file.createNewFile();
    }

    ByteBuf byteBuf = (ByteBuf) msg;
    ByteBuffer byteBuffer = byteBuf.nioBuffer();
    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
    FileChannel fileChannel = randomAccessFile.getChannel();

    while (byteBuffer.hasRemaining()){;
        fileChannel.position(file.length());
        fileChannel.write(byteBuffer);
    }

    byteBuf.release();
    fileChannel.close();
    randomAccessFile.close();

}}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!