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));
}
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.
- use ByteBuf to receive the ChunkFile or FileRegion and convert it to ByteBuffer which is java nio.
- 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();
}}
来源:https://stackoverflow.com/questions/25888260/netty-how-to-handle-received-chunks-from-a-chunkedfile