我尝试使用以下代码:
saver=new FileOutputStream(file);
byte c;
while ( content.readable() ){ //content is a ChannelBuffer type
c = content.readByte();
saver.write(c);
}
但是由于文件流是二进制的,因此写入速度似乎真的很慢!有没有办法将通道缓冲区保存到文件中非常快?
尝试将整个缓冲区写入文件。 此示例代码来自 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();
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();
}