2

我曾尝试使用此代码:

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

但是由于文件流是二进制的,所以写入速度似乎真的很慢!有什么方法可以真正快速地将 ChannelBuffer 保存到文件中?

4

2 回答 2

8

尝试将整个缓冲区写入文件。此示例代码来自 netty 文件上传应用程序

    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();
于 2012-05-06T02:59:10.790 回答
2
    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();
    }
于 2013-05-23T08:55:29.723 回答