本文整理匯總了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);
}
}
示例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);
}
}
示例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();
}
示例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();
}
}
示例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;
}
示例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;
}
示例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;
}
示例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();
}
示例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();
}
示例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();
}
}
}
示例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;
}
示例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;
}
示例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);
}
示例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();
}
}
示例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);
}