001
014
015 package com.liferay.portal.kernel.io.delta;
016
017 import java.io.IOException;
018
019 import java.nio.ByteBuffer;
020 import java.nio.channels.WritableByteChannel;
021
022
025 public class ByteChannelWriter {
026
027 public ByteChannelWriter(WritableByteChannel writableByteChannel) {
028 this(writableByteChannel, 1024);
029 }
030
031 public ByteChannelWriter(
032 WritableByteChannel writableByteChannel, int bufferLength) {
033
034 _writableByteChannel = writableByteChannel;
035
036 _byteBuffer = ByteBuffer.allocate(bufferLength);
037 }
038
039 public void ensureSpace(int length) throws IOException {
040 if (_byteBuffer.remaining() < length) {
041 write();
042 }
043 }
044
045 public void finish() throws IOException {
046 _byteBuffer.flip();
047
048 _writableByteChannel.write(_byteBuffer);
049 }
050
051 public ByteBuffer getBuffer() {
052 return _byteBuffer;
053 }
054
055 public void resizeBuffer(int minBufferLength) {
056 if (_byteBuffer.capacity() >= minBufferLength) {
057 return;
058 }
059
060 ByteBuffer newBuffer = ByteBuffer.allocate(minBufferLength);
061
062 _byteBuffer.flip();
063
064 newBuffer.put(_byteBuffer);
065
066 _byteBuffer = newBuffer;
067 }
068
069 protected void write() throws IOException {
070 _byteBuffer.flip();
071
072 _writableByteChannel.write(_byteBuffer);
073
074 _byteBuffer.clear();
075 }
076
077 private ByteBuffer _byteBuffer;
078 private WritableByteChannel _writableByteChannel;
079
080 }