当前位置: 首页>>代码示例>>Java>>正文


Java CharBuffer.capacity方法代码示例

本文整理汇总了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();
}
 
开发者ID:Netflix,项目名称:sstable-adaptor,代码行数:29,代码来源:CBUtil.java

示例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;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:12,代码来源:Chars.java

示例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;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:12,代码来源:Chars.java

示例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");
}
 
开发者ID:moueimei,项目名称:flume-release-1.7.0,代码行数:57,代码来源:NetcatSource.java

示例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 ) ;
            }
        }
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:52,代码来源:CodeSetConversion.java

示例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
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:60,代码来源:BaseFileManager.java


注:本文中的java.nio.CharBuffer.capacity方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。