【问题标题】:netty - How to save the ChannelBuffer type to the file?netty - 如何将 ChannelBuffer 类型保存到文件中?
【发布时间】:2012-05-06 01:34:23
【问题描述】:

我已尝试使用此代码:

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

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

【问题讨论】:

  • 尽量不要一次写入一个字节。流是“二进制”的事实与它无关;你需要读/写更大的块。
  • 正确。我表达的不是很清楚,二进制的意思是数据是一个块,我怎么能把它写成更大的块呢?我的意思是,我想将 ChannelBuffer 中的所有字节保存到文件中,但是如何?

标签: java networking network-programming netty


【解决方案1】:

尝试将整个缓冲区写入文件。此示例代码来自 netty 文件上传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();

【讨论】:

    【解决方案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();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-28
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-27
      • 2012-11-09
      • 1970-01-01
      相关资源
      最近更新 更多