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


Java CharBuffer.clear方法代码示例

本文整理汇总了Java中java.nio.CharBuffer.clear方法的典型用法代码示例。如果您正苦于以下问题:Java CharBuffer.clear方法的具体用法?Java CharBuffer.clear怎么用?Java CharBuffer.clear使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.nio.CharBuffer的用法示例。


在下文中一共展示了CharBuffer.clear方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: byCharsetEncoder_US_ASCII

import java.nio.CharBuffer; //导入方法依赖的package包/类
@Benchmark
public byte[] byCharsetEncoder_US_ASCII() {
    try {
        CharsetEncoder encoder = asciiencode.get();
        CharBuffer buffer  = charbuffergenerator.get();
        buffer.clear();
        buffer.append(STR);
        buffer.flip();

        ByteBuffer outbuffer = bytebuffergenerator.get();
        outbuffer.clear();

        CoderResult result = encoder.encode(buffer, outbuffer, false);
        if (result.isError()) {
            result.throwException();
        }
        byte[] b = new byte[STR.length()];
        outbuffer.flip();
        outbuffer.get(b);
        return b;
    } catch (CharacterCodingException e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:fbacchella,项目名称:RegexPerf,代码行数:25,代码来源:StringToBytes.java

示例2: toString

import java.nio.CharBuffer; //导入方法依赖的package包/类
/**
 * Adapted from {@code com.google.common.io.CharStreams.toString()}.
 */
public static String toString(Reader reader) throws IOException {
  if (reader == null) {
    return null;
  }
  try {
    StringBuilder to = new StringBuilder();
    CharBuffer buf = CharBuffer.allocate(BUF_SIZE);
    while (reader.read(buf) != -1) {
      buf.flip();
      to.append(buf);
      buf.clear();
    }
    return to.toString();
  } finally {
    ensureClosed(reader);
  }
}
 
开发者ID:wenwu315,项目名称:XXXX,代码行数:21,代码来源:Util.java

示例3: 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

示例4: byte2char

import java.nio.CharBuffer; //导入方法依赖的package包/类
private void byte2char(ByteBuffer bytes, CharBuffer chars) throws IOException {
    decoder.reset();
    chars.clear();
    CoderResult result = decoder.decode(bytes, chars, true);
    if (result.isError() || result.isOverflow()) {
        throw new IOException(result.toString());
    } else if (result.isUnderflow()) {
        chars.flip();
    }
}
 
开发者ID:jalian-systems,项目名称:marathonv5,代码行数:11,代码来源:WriterOutputStream.java

示例5: loadPrivateKey

import java.nio.CharBuffer; //导入方法依赖的package包/类
/**
 * Load private pkcs8 pem file to get the private key
 *
 * @param fileStream InputStream of the Pkcs8 file
 * @return Key to construct YfyEnterpriseAuth and used in signature
 * @throws Exception
 */
public static PrivateKey loadPrivateKey(InputStream fileStream) throws Exception {
    String privateKeyPEM;
    Reader reader = new InputStreamReader(fileStream);
    try {
        StringBuilder stringBuilder = new StringBuilder();

        CharBuffer buffer = CharBuffer.allocate(2048);
        while (reader.read(buffer) != -1) {
            buffer.flip();
            stringBuilder.append(buffer);
            buffer.clear();
        }
        privateKeyPEM = stringBuilder.toString();
    } finally {
        reader.close();
    }

    // strip of header, footer, newlines, whitespaces
    privateKeyPEM = privateKeyPEM
            .replace("-----BEGIN PRIVATE KEY-----", "")
            .replace("-----END PRIVATE KEY-----", "")
            .replaceAll("\\s", "");

    // decode to get the binary DER representation
    byte[] privateKeyDER = Base64.decodeBase64(privateKeyPEM);

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyDER));
    return privateKey;
}
 
开发者ID:yifangyun,项目名称:fangcloud-java-sdk,代码行数:38,代码来源:YfyEnterpriseAuth.java

示例6: copy

import java.nio.CharBuffer; //导入方法依赖的package包/类
/**
 * Copies all characters between the {@link Readable} and {@link Appendable} objects. Does not
 * close or flush either object.
 *
 * @param from the object to read from
 * @param to the object to write to
 * @return the number of characters copied
 * @throws IOException if an I/O error occurs
 */
@CanIgnoreReturnValue
public static long copy(Readable from, Appendable to) throws IOException {
  checkNotNull(from);
  checkNotNull(to);
  CharBuffer buf = createBuffer();
  long total = 0;
  while (from.read(buf) != -1) {
    buf.flip();
    to.append(buf);
    total += buf.remaining();
    buf.clear();
  }
  return total;
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:24,代码来源:CharStreams.java

示例7: exhaust

import java.nio.CharBuffer; //导入方法依赖的package包/类
/**
 * Reads and discards data from the given {@code Readable} until the end of the stream is
 * reached. Returns the total number of chars read. Does not close the stream.
 *
 * @since 20.0
 */
@CanIgnoreReturnValue
public static long exhaust(Readable readable) throws IOException {
  long total = 0;
  long read;
  CharBuffer buf = createBuffer();
  while ((read = readable.read(buf)) != -1) {
    total += read;
    buf.clear();
  }
  return total;
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:18,代码来源:CharStreams.java

示例8: getSinkContents

import java.nio.CharBuffer; //导入方法依赖的package包/类
@Override
public String getSinkContents() throws IOException {
  File file = getFile();
  Reader reader = new InputStreamReader(new FileInputStream(file), Charsets.UTF_8);
  StringBuilder builder = new StringBuilder();
  CharBuffer buffer = CharBuffer.allocate(100);
  while (reader.read(buffer) != -1) {
    buffer.flip();
    builder.append(buffer);
    buffer.clear();
  }
  return builder.toString();
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:14,代码来源:SourceSinkFactories.java

示例9: test

import java.nio.CharBuffer; //导入方法依赖的package包/类
private static void test(CharBuffer cb, String exp) {
    cb.limit(cb.position());
    cb.rewind();
    if (!cb.toString().equals(exp))
        throw new RuntimeException("expect: '" + exp + "'; got: '"
                                   + cb.toString() + "'");
    cb.clear();
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:9,代码来源:StockName.java

示例10: stringIdentity

import java.nio.CharBuffer; //导入方法依赖的package包/类
@Test
public void stringIdentity() {
    final int MAX_STRING_LENGTH = 4096;
    ByteBuffer bytes = ByteBuffer.allocate(MAX_STRING_LENGTH + 6); // it takes 6 bytes to encode string length of Integer.MAX_VALUE
    CharBuffer chars = CharBuffer.allocate(MAX_STRING_LENGTH);
    StringReader reader = new StringReader();
    StringWriter writer = new StringWriter();
    for (int len = 0; len <= MAX_STRING_LENGTH; len++) {
        for (int i = 0; i < 64; i++) {
            // not so much "test in isolation", I know... we're testing .reset() as well
            bytes.clear();
            chars.clear();

            byte[] b = new byte[len];
            rnd.nextBytes(b);

            String expected = new String(b, StandardCharsets.ISO_8859_1); // reference string

            boolean written = writer
                    .configure(CharBuffer.wrap(expected), 0, expected.length(), false)
                    .write(bytes);

            if (!written) {
                fail("please increase 'bytes' size");
            }
            bytes.flip();
            reader.read(bytes, chars);
            chars.flip();
            assertEquals(chars.toString(), expected);
            reader.reset();
            writer.reset();
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:35,代码来源:BinaryPrimitivesTest.java

示例11: length

import java.nio.CharBuffer; //导入方法依赖的package包/类
/**
 * Compute lenght of this sequence - quite expensive operation, indeed.
 */
@Override
public int length() {
    if (length != -1) {
        return length;
    }
    long start = System.currentTimeMillis();
    int charactersRead = 0;
    long bytesRead = 0;
    MappedByteBuffer mappedByteBuffer = null;
    CharBuffer charBuffer = CharBuffer.allocate(SIZE_LIMIT);
    CharsetDecoder decoder = prepareDecoder(charset);
    decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);

    try {
        while (bytesRead < fileSize) {
            mappedByteBuffer = fileChannel.map(
                    FileChannel.MapMode.READ_ONLY, bytesRead,
                    Math.min(SIZE_LIMIT, fileSize - bytesRead));
            CoderResult result;
            do {
                charBuffer.clear();
                result = decoder.decode(
                        mappedByteBuffer, charBuffer,
                        bytesRead + SIZE_LIMIT >= fileSize);
                if (result.isUnmappable() || result.isMalformed()
                        || result.isError()) {
                    throw new IOException("Error decoding file: "
                            + result.toString() + " ");
                }
                if (bytesRead + SIZE_LIMIT >= fileSize) {
                    LOG.info("Coding end");
                }
                charactersRead += charBuffer.position();
            } while (result.isOverflow());

            int readNow = mappedByteBuffer.position();
            bytesRead += readNow;
            unmap(mappedByteBuffer);
        }
        charBuffer.clear();
        boolean repeat;
        do {
            repeat = decoder.flush(charBuffer).isOverflow();
            charactersRead += charBuffer.position();
            charBuffer.clear();
        } while (repeat);
    } catch (IOException ex) {
        if (mappedByteBuffer != null) {
            unmap(mappedByteBuffer);
        }
        Exceptions.printStackTrace(ex);
    }
    length = charactersRead;
    LOG.log(Level.INFO, "Length computed in {0} ms.", //NOI18N
            System.currentTimeMillis() - start);
    return length;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:61,代码来源:FastMatcher.java

示例12: read

import java.nio.CharBuffer; //导入方法依赖的package包/类
public int read(final char[] cbuf, final int off,
                int len) throws IOException {

    final long l_remaining = m_remaining;

    if (l_remaining <= 0) {
        return -1;
    } else if (l_remaining < len) {
        len = (int) l_remaining;
    }

    int charsRead = m_reader.read(cbuf, off, len);

    if (charsRead == -1) {
        return -1;
    } else if (charsRead > l_remaining) {
        charsRead   = (int) l_remaining;
        m_remaining = 0;
    } else {
        m_remaining -= charsRead;
    }

    int bytesRead;

    if (m_fixedWidthCharset) {
        bytesRead = (m_maxCharWidth * charsRead);
    } else {
        final boolean reallocate = (charsRead
                                    > m_charBuffer.capacity());
        final CharBuffer cb = reallocate
                              ? CharBuffer.allocate(charsRead)
                              : m_charBuffer;
        final ByteBuffer bb = reallocate
                              ? ByteBuffer.allocate(charsRead
                                  * m_maxCharWidth)
                              : m_byteBuffer;

        //
        cb.clear();
        bb.clear();
        cb.put(cbuf, off, charsRead);
        cb.flip();
        m_encoder.encode(cb, bb, /*endOfinput*/ true);
        bb.flip();

        bytesRead = bb.limit();

        if (reallocate) {
            m_byteBuffer = bb;
            m_charBuffer = cb;
        }
    }

    m_filePointer += bytesRead;

    return charsRead;
}
 
开发者ID:tiweGH,项目名称:OpenDiabetes,代码行数:58,代码来源:JDBCClobFile.java

示例13: decodeLoop

import java.nio.CharBuffer; //导入方法依赖的package包/类
protected CoderResult decodeLoop(ByteBuffer src, CharBuffer dst) {
    if (detectedDecoder == null) {
        copyLeadingASCII(src, dst);

        // All ASCII?
        if (! src.hasRemaining())
            return CoderResult.UNDERFLOW;
        if (! dst.hasRemaining())
            return CoderResult.OVERFLOW;

        // We need to perform double, not float, arithmetic; otherwise
        // we lose low order bits when src is larger than 2**24.
        int cbufsiz = (int)(src.limit() * (double)maxCharsPerByte());
        CharBuffer sandbox = CharBuffer.allocate(cbufsiz);

        // First try ISO-2022-JP, since there is no ambiguity
        Charset cs2022 = Charset.forName("ISO-2022-JP");
        DelegatableDecoder dd2022
            = (DelegatableDecoder) cs2022.newDecoder();
        ByteBuffer src2022 = src.asReadOnlyBuffer();
        CoderResult res2022 = dd2022.decodeLoop(src2022, sandbox);
        if (! res2022.isError())
            return decodeLoop(cs2022, src, dst);

        // We must choose between EUC and SJIS
        Charset csEUCJ = Charset.forName(EUCJPName);
        Charset csSJIS = Charset.forName(SJISName);

        DelegatableDecoder ddEUCJ
            = (DelegatableDecoder) csEUCJ.newDecoder();
        ByteBuffer srcEUCJ = src.asReadOnlyBuffer();
        sandbox.clear();
        CoderResult resEUCJ = ddEUCJ.decodeLoop(srcEUCJ, sandbox);
        // If EUC decoding fails, must be SJIS
        if (resEUCJ.isError())
            return decodeLoop(csSJIS, src, dst);

        DelegatableDecoder ddSJIS
            = (DelegatableDecoder) csSJIS.newDecoder();
        ByteBuffer srcSJIS = src.asReadOnlyBuffer();
        CharBuffer sandboxSJIS = CharBuffer.allocate(cbufsiz);
        CoderResult resSJIS = ddSJIS.decodeLoop(srcSJIS, sandboxSJIS);
        // If SJIS decoding fails, must be EUC
        if (resSJIS.isError())
            return decodeLoop(csEUCJ, src, dst);

        // From here on, we have some ambiguity, and must guess.

        // We prefer input that does not appear to end mid-character.
        if (srcEUCJ.position() > srcSJIS.position())
            return decodeLoop(csEUCJ, src, dst);

        if (srcEUCJ.position() < srcSJIS.position())
            return decodeLoop(csSJIS, src, dst);

        // end-of-input is after the first byte of the first char?
        if (src.position() == srcEUCJ.position())
            return CoderResult.UNDERFLOW;

        // Use heuristic knowledge of typical Japanese text
        sandbox.flip();
        Charset guess = looksLikeJapanese(sandbox) ? csEUCJ : csSJIS;
        return decodeLoop(guess, src, dst);
    }

    return detectedDecoder.decodeLoop(src, dst);
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:68,代码来源:JISAutoDetect.java

示例14: testHProfFileFormat

import java.nio.CharBuffer; //导入方法依赖的package包/类
private static void testHProfFileFormat(String vmArgs, long heapSize,
        String expectedFormat) throws Exception, IOException,
        InterruptedException, FileNotFoundException {
    ProcessBuilder procBuilder = ProcessTools.createJavaProcessBuilder(
            "--add-exports=java.management/sun.management=ALL-UNNAMED", vmArgs, "JMapHProfLargeHeapProc", String.valueOf(heapSize));
    procBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
    Process largeHeapProc = procBuilder.start();

    try (Scanner largeHeapScanner = new Scanner(
            largeHeapProc.getInputStream());) {
        String pidstring = null;
        if (!largeHeapScanner.hasNext()) {
            throw new RuntimeException ("Test failed: could not open largeHeapScanner.");
        }
        while ((pidstring = largeHeapScanner.findInLine("PID\\[[0-9].*\\]")) == null) {
            Thread.sleep(500);
        }
        int pid = Integer.parseInt(pidstring.substring(4,
                pidstring.length() - 1));
        System.out.println("Extracted pid: " + pid);

        JDKToolLauncher jMapLauncher = JDKToolLauncher
                .createUsingTestJDK("jhsdb");
        jMapLauncher.addToolArg("jmap");
        jMapLauncher.addToolArg("--binaryheap");
        jMapLauncher.addToolArg("--pid");
        jMapLauncher.addToolArg(String.valueOf(pid));

        ProcessBuilder jMapProcessBuilder = new ProcessBuilder(
                jMapLauncher.getCommand());
        System.out.println("jmap command: "
                + Arrays.toString(jMapLauncher.getCommand()));

        Process jMapProcess = jMapProcessBuilder.start();
        OutputAnalyzer analyzer = new OutputAnalyzer(jMapProcess);
        analyzer.shouldHaveExitValue(0);
        analyzer.shouldContain(HEAP_DUMP_FILE_NAME);

        largeHeapProc.getOutputStream().write('\n');

        File dumpFile = new File(HEAP_DUMP_FILE_NAME);
        Asserts.assertTrue(dumpFile.exists(), "Heap dump file not found.");

        try (Reader reader = new BufferedReader(new FileReader(dumpFile))) {
            CharBuffer buf = CharBuffer.allocate(expectedFormat.length());
            reader.read(buf);
            buf.clear();
            Asserts.assertEQ(buf.toString(), expectedFormat,
                    "Wrong file format. Expected '" + expectedFormat
                            + "', but found '" + buf.toString() + "'");
        }

        System.out.println("Success!");

    } finally {
        largeHeapProc.destroyForcibly();
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:59,代码来源:JMapHProfLargeHeapTest.java

示例15: decodeLoop

import java.nio.CharBuffer; //导入方法依赖的package包/类
protected CoderResult decodeLoop(ByteBuffer src, CharBuffer dst) {
    if (detectedDecoder == null) {
        copyLeadingASCII(src, dst);

        // All ASCII?
        if (! src.hasRemaining())
            return CoderResult.UNDERFLOW;
        // Overflow only if there is still ascii but no out buffer.
        if (!dst.hasRemaining() &&
            isPlainASCII(src.get(src.position())))
            return CoderResult.OVERFLOW;

        // We need to perform double, not float, arithmetic; otherwise
        // we lose low order bits when src is larger than 2**24.
        int cbufsiz = (int)(src.limit() * (double)maxCharsPerByte());
        CharBuffer sandbox = CharBuffer.allocate(cbufsiz);

        // First try ISO-2022-JP, since there is no ambiguity
        Charset cs2022 = Charset.forName("ISO-2022-JP");
        DelegatableDecoder dd2022
            = (DelegatableDecoder) cs2022.newDecoder();
        ByteBuffer src2022 = src.asReadOnlyBuffer();
        CoderResult res2022 = dd2022.decodeLoop(src2022, sandbox);
        if (! res2022.isError())
            return decodeLoop(dd2022, src, dst);

        // We must choose between EUC and SJIS
        Charset csEUCJ = Charset.forName(EUCJPName);
        Charset csSJIS = Charset.forName(SJISName);

        DelegatableDecoder ddEUCJ
            = (DelegatableDecoder) csEUCJ.newDecoder();
        DelegatableDecoder ddSJIS
            = (DelegatableDecoder) csSJIS.newDecoder();

        ByteBuffer srcEUCJ = src.asReadOnlyBuffer();
        sandbox.clear();
        CoderResult resEUCJ = ddEUCJ.decodeLoop(srcEUCJ, sandbox);
        // If EUC decoding fails, must be SJIS
        if (resEUCJ.isError())
            return decodeLoop(ddSJIS, src, dst);
        ByteBuffer srcSJIS = src.asReadOnlyBuffer();
        CharBuffer sandboxSJIS = CharBuffer.allocate(cbufsiz);
        CoderResult resSJIS = ddSJIS.decodeLoop(srcSJIS, sandboxSJIS);
        // If SJIS decoding fails, must be EUC
        if (resSJIS.isError())
            return decodeLoop(ddEUCJ, src, dst);

        // From here on, we have some ambiguity, and must guess.

        // We prefer input that does not appear to end mid-character.
        if (srcEUCJ.position() > srcSJIS.position())
            return decodeLoop(ddEUCJ, src, dst);

        if (srcEUCJ.position() < srcSJIS.position())
            return decodeLoop(ddSJIS, src, dst);

        // end-of-input is after the first byte of the first char?
        if (src.position() == srcEUCJ.position())
            return CoderResult.UNDERFLOW;

        // Use heuristic knowledge of typical Japanese text
        sandbox.flip();
        return decodeLoop(looksLikeJapanese(sandbox) ? ddEUCJ : ddSJIS,
                          src, dst);
    }

    return detectedDecoder.decodeLoop(src, dst);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:70,代码来源:JISAutoDetect.java


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