Last active
August 29, 2015 14:03
-
-
Save a-chernykh/73d4f56244fc6848ef86 to your computer and use it in GitHub Desktop.
Buffered WritableByteChannel implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static class BufferedWritableFileByteChannel implements WritableByteChannel { | |
private static final int BUFFER_CAPACITY = 1000000; | |
private boolean isOpen = true; | |
private final OutputStream outputStream; | |
private final ByteBuffer byteBuffer; | |
private final byte[] rawBuffer = new byte[BUFFER_CAPACITY]; | |
private BufferedWritableFileByteChannel(OutputStream outputStream) { | |
this.outputStream = outputStream; | |
this.byteBuffer = ByteBuffer.wrap(rawBuffer); | |
} | |
@Override | |
public int write(ByteBuffer inputBuffer) throws IOException { | |
int inputBytes = inputBuffer.remaining(); | |
if (inputBytes > byteBuffer.remaining()) { | |
dumpToFile(); | |
byteBuffer.clear(); | |
if (inputBytes > byteBuffer.remaining()) { | |
throw new BufferOverflowException(); | |
} | |
} | |
byteBuffer.put(inputBuffer); | |
return inputBytes; | |
} | |
@Override | |
public boolean isOpen() { | |
return isOpen; | |
} | |
@Override | |
public void close() throws IOException { | |
dumpToFile(); | |
isOpen = false; | |
} | |
private void dumpToFile() { | |
try { | |
outputStream.write(rawBuffer, 0, byteBuffer.position()); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment