Search code examples
nettyfile-transferchunks

Netty: How to handle received chunks from a ChunkedFile


I am new to netty and I am attempting to transfer a chunkedfile from a server to a client. Sending the chunks work just fine. The problem is on how to handle the received chunks and write them to a file. Both methods that I tried give me a direct buffer error.

Any help would be greatly appreciated.

Thanks!

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

         System.out.println(in.toString());


         //METHOD 1: write to file
         FileOutputStream fos = new FileOutputStream("c:\\test.txt");
         fos.write(in.array());


         //METHOD 2: getting desperate   
         //InputStream inputStream = new ByteBufInputStream(in); 
         //ChunkedStream chkStream = new ChunkedStream(inputStream);             
         //outputStream.write( (chkStream.readChunk(ctx).readBytes(in, 0)).array());

         //if(chkStream.isEndOfInput()){
         //  outputStream.close();
         //  inputStream.close();
         //  chkStream.close();
         //}


         return;

     }

     out.add(in.toString(charset));

}

Solution

  • 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();