Java Reference
In-Depth Information
public static void encode(DataSourceSink ds, String charset) {
CharsetEncoder encoder = Charset.forName(charset).newEncoder();
CharBuffer input = CharBuffer.allocate(8);
ByteBuffer output = ByteBuffer.allocate(8);
// Initialize variables for loop
boolean endOfInput = false;
CoderResult result = CoderResult.UNDERFLOW;
while (!endOfInput) {
if (result == CoderResult.UNDERFLOW) {
input.clear();
endOfInput = (ds.getCharData(input) == -1);
input.flip();
}
// Encode the input characters
result = encoder.encode(input, output, endOfInput);
// Drain output when
// 1. It is an overflow. Or,
// 2. It is an underflow and it is the end of the input
if (result == CoderResult.OVERFLOW ||
(endOfInput && result == CoderResult.UNDERFLOW)) {
output.flip();
ds.storeByteData(output);
output.clear();
}
}
// Flush the internal state of the encoder
while (true) {
output.clear();
result = encoder.flush(output);
output.flip();
if (output.hasRemaining()) {
ds.storeByteData(output);
output.clear();
}
// Underflow means flush() method has flushed everything
if (result == CoderResult.UNDERFLOW) {
break;
}
}
}
Search WWH ::




Custom Search