本文整理匯總了Java中java.nio.CharBuffer.capacity方法的典型用法代碼示例。如果您正苦於以下問題:Java CharBuffer.capacity方法的具體用法?Java CharBuffer.capacity怎麽用?Java CharBuffer.capacity使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.nio.CharBuffer
的用法示例。
在下文中一共展示了CharBuffer.capacity方法的6個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: decodeString
import java.nio.CharBuffer; //導入方法依賴的package包/類
private static String decodeString(ByteBuffer src) throws CharacterCodingException
{
// the decoder needs to be reset every time we use it, hence the copy per thread
CharsetDecoder theDecoder = TL_UTF8_DECODER.get();
theDecoder.reset();
CharBuffer dst = TL_CHAR_BUFFER.get();
int capacity = (int) ((double) src.remaining() * theDecoder.maxCharsPerByte());
if (dst == null)
{
capacity = Math.max(capacity, 4096);
dst = CharBuffer.allocate(capacity);
TL_CHAR_BUFFER.set(dst);
}
else
{
dst.clear();
if (dst.capacity() < capacity)
{
dst = CharBuffer.allocate(capacity);
TL_CHAR_BUFFER.set(dst);
}
}
CoderResult cr = theDecoder.decode(src, dst, true);
if (!cr.isUnderflow())
cr.throwException();
return dst.flip().toString();
}
示例2: randomizeRange
import java.nio.CharBuffer; //導入方法依賴的package包/類
/**
* Randomize the char buffer's position and limit.
*/
static CharBuffer randomizeRange(CharBuffer cb) {
int mid = cb.capacity() >>> 1;
int start = RAND.nextInt(mid);
int end = mid + RAND.nextInt(mid);
cb.position(start);
cb.limit(end);
return cb;
}
示例3: randomizeRange
import java.nio.CharBuffer; //導入方法依賴的package包/類
/**
* Randomize the char buffer's position and limit.
*/
static CharBuffer randomizeRange(CharBuffer cb) {
int mid = cb.capacity() >>> 1;
int start = RAND.nextInt(mid + 1); // from 0 to mid
int end = mid + RAND.nextInt(cb.capacity() - mid + 1); // from mid to capacity
cb.position(start);
cb.limit(end);
return cb;
}
示例4: run
import java.nio.CharBuffer; //導入方法依賴的package包/類
@Override
public void run() {
logger.debug("Starting connection handler");
Event event = null;
try {
Reader reader = Channels.newReader(socketChannel, sourceEncoding);
Writer writer = Channels.newWriter(socketChannel, sourceEncoding);
CharBuffer buffer = CharBuffer.allocate(maxLineLength);
buffer.flip(); // flip() so fill() sees buffer as initially empty
while (true) {
// this method blocks until new data is available in the socket
int charsRead = fill(buffer, reader);
logger.debug("Chars read = {}", charsRead);
// attempt to process all the events in the buffer
int eventsProcessed = processEvents(buffer, writer);
logger.debug("Events processed = {}", eventsProcessed);
if (charsRead == -1) {
// if we received EOF before last event processing attempt, then we
// have done everything we can
break;
} else if (charsRead == 0 && eventsProcessed == 0) {
if (buffer.remaining() == buffer.capacity()) {
// If we get here it means:
// 1. Last time we called fill(), no new chars were buffered
// 2. After that, we failed to process any events => no newlines
// 3. The unread data in the buffer == the size of the buffer
// Therefore, we are stuck because the client sent a line longer
// than the size of the buffer. Response: Drop the connection.
logger.warn("Client sent event exceeding the maximum length");
counterGroup.incrementAndGet("events.failed");
writer.write("FAILED: Event exceeds the maximum length (" +
buffer.capacity() + " chars, including newline)\n");
writer.flush();
break;
}
}
}
socketChannel.close();
counterGroup.incrementAndGet("sessions.completed");
} catch (IOException e) {
counterGroup.incrementAndGet("sessions.broken");
try {
socketChannel.close();
} catch (IOException ex) {
logger.error("Unable to close socket channel. Exception follows.", ex);
}
}
logger.debug("Connection handler exiting");
}
示例5: getChars
import java.nio.CharBuffer; //導入方法依賴的package包/類
public char[] getChars(byte[] bytes, int offset, int numBytes) {
// Possible optimization of reading directly from the CDR
// byte buffer. The sun.io converter supposedly can handle
// incremental conversions in which a char is broken across
// two convert calls.
//
// Basic tests didn't show more than a 1 ms increase
// worst case. It's less than a factor of 2 increase.
// Also makes the interface more difficult.
try {
ByteBuffer byteBuf = ByteBuffer.wrap(bytes, offset, numBytes);
CharBuffer charBuf = btc.decode(byteBuf);
// CharBuffer returned by the decoder will set its limit
// to byte immediately after the last written byte.
resultingNumChars = charBuf.limit();
// IMPORTANT - It's possible the underlying char[] in the
// CharBuffer returned by btc.decode(byteBuf)
// is longer in length than the number of characters
// decoded. Hence, the check below to ensure the
// char[] returned contains all the chars that have
// been decoded and no more.
if (charBuf.limit() == charBuf.capacity()) {
buffer = charBuf.array();
} else {
buffer = new char[charBuf.limit()];
charBuf.get(buffer, 0, charBuf.limit()).position(0);
}
return buffer;
} catch (IllegalStateException ile) {
// There were a decoding operation already in progress
throw wrapper.btcConverterFailure( ile ) ;
} catch (MalformedInputException mie) {
// There were illegal Unicode char pairs
throw wrapper.badUnicodePair( mie ) ;
} catch (UnmappableCharacterException uce) {
// A character doesn't map to the desired code set.
// CORBA formal 00-11-03.
throw omgWrapper.charNotInCodeset( uce ) ;
} catch (CharacterCodingException cce) {
// If this happens, then a character decoding error occured.
throw wrapper.btcConverterFailure( cce ) ;
}
}
示例6: decode
import java.nio.CharBuffer; //導入方法依賴的package包/類
@SuppressWarnings("cast")
public CharBuffer decode(ByteBuffer inbuf, boolean ignoreEncodingErrors) {
String encName = getEncodingName();
CharsetDecoder decoder;
try {
decoder = getDecoder(encName, ignoreEncodingErrors);
} catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
log.error(Errors.UnsupportedEncoding(encName));
return (CharBuffer)CharBuffer.allocate(1).flip();
}
// slightly overestimate the buffer size to avoid reallocation.
float factor =
decoder.averageCharsPerByte() * 0.8f +
decoder.maxCharsPerByte() * 0.2f;
CharBuffer dest = CharBuffer.
allocate(10 + (int)(inbuf.remaining()*factor));
while (true) {
CoderResult result = decoder.decode(inbuf, dest, true);
dest.flip();
if (result.isUnderflow()) { // done reading
// make sure there is at least one extra character
if (dest.limit() == dest.capacity()) {
dest = CharBuffer.allocate(dest.capacity()+1).put(dest);
dest.flip();
}
return dest;
} else if (result.isOverflow()) { // buffer too small; expand
int newCapacity =
10 + dest.capacity() +
(int)(inbuf.remaining()*decoder.maxCharsPerByte());
dest = CharBuffer.allocate(newCapacity).put(dest);
} else if (result.isMalformed() || result.isUnmappable()) {
// bad character in input
StringBuilder unmappable = new StringBuilder();
int len = result.length();
for (int i = 0; i < len; i++) {
unmappable.append(String.format("%02X", inbuf.get()));
}
String charsetName = charset == null ? encName : charset.name();
log.error(dest.limit(),
Errors.IllegalCharForEncoding(unmappable.toString(), charsetName));
// undo the flip() to prepare the output buffer
// for more translation
dest.position(dest.limit());
dest.limit(dest.capacity());
dest.put((char)0xfffd); // backward compatible
} else {
throw new AssertionError(result);
}
}
// unreached
}