netty - 如何将ChannelBuffer类型保存到文件中?

时间:2012-05-06 01:34:23

标签: java networking network-programming netty

我试过使用这段代码:

saver=new FileOutputStream(file);
byte c;
while ( content.readable() ){ //content is a ChannelBuffer type
    c = content.readByte();
    saver.write(c); 
   }   

但由于文件流是二进制文件,因此写入速度似乎很慢!有没有办法将ChannelBuffer快速保存到文件中?

2 个答案:

答案 0 :(得分:7)

尝试将整个缓冲区写入文件。此示例代码来自netty file upload app

    FileOutputStream outputStream = new FileOutputStream(file);
    FileChannel localfileChannel = outputStream.getChannel();
    ByteBuffer byteBuffer = buffer.toByteBuffer();
    int written = 0;
    while (written < size) {
        written += localfileChannel.write(byteBuffer);
    }
    buffer.readerIndex(buffer.readerIndex() + written);
    localfileChannel.force(false);
    localfileChannel.close();

答案 1 :(得分:1)

    ChannelBuffer cBuffer = ***;

    try (FileOutputStream foStream = new FileOutputStream(filepath)) {
        while (cBuffer.readable()) {
            byte[] bb = new byte[cBuffer.readableBytes()];
            cBuffer.readBytes(bb);
            foStream.write(bb);
        }
        foStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }