本文整理匯總了Java中java.nio.CharBuffer.wrap方法的典型用法代碼示例。如果您正苦於以下問題:Java CharBuffer.wrap方法的具體用法?Java CharBuffer.wrap怎麽用?Java CharBuffer.wrap使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.nio.CharBuffer
的用法示例。
在下文中一共展示了CharBuffer.wrap方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: writeLine
import java.nio.CharBuffer; //導入方法依賴的package包/類
/**
* Writes characters from the specified char array followed by a line
* delimiter to this session buffer.
* <p>
* This method uses CR-LF as a line delimiter.
*
* @param charbuffer the buffer containing chars of the line.
* @exception IOException if an I/O error occurs.
*/
public void writeLine(final CharArrayBuffer charbuffer) throws IOException {
if (charbuffer == null) {
return;
}
if (this.ascii) {
int off = 0;
int remaining = charbuffer.length();
while (remaining > 0) {
int chunk = this.buffer.capacity() - this.buffer.length();
chunk = Math.min(chunk, remaining);
if (chunk > 0) {
this.buffer.append(charbuffer, off, chunk);
}
if (this.buffer.isFull()) {
flushBuffer();
}
off += chunk;
remaining -= chunk;
}
} else {
CharBuffer cbuf = CharBuffer.wrap(charbuffer.buffer(), 0, charbuffer.length());
writeEncoded(cbuf);
}
write(CRLF);
}
示例2: getBytes
import java.nio.CharBuffer; //導入方法依賴的package包/類
byte[] getBytes(String s) {
CharsetEncoder ce = encoder().reset();
char[] ca = s.toCharArray();
int len = (int)(ca.length * ce.maxBytesPerChar());
byte[] ba = new byte[len];
if (len == 0)
return ba;
ByteBuffer bb = ByteBuffer.wrap(ba);
CharBuffer cb = CharBuffer.wrap(ca);
CoderResult cr = ce.encode(cb, bb, true);
if (!cr.isUnderflow())
throw new IllegalArgumentException(cr.toString());
cr = ce.flush(bb);
if (!cr.isUnderflow())
throw new IllegalArgumentException(cr.toString());
if (bb.position() == ba.length) // defensive copy?
return ba;
else
return Arrays.copyOf(ba, bb.position());
}
示例3: memoryFileObject
import java.nio.CharBuffer; //導入方法依賴的package包/類
/**
* Creates virtual {@link JavaFileObject} with given name and content.
* This method should be used only by tests, regular client should never
* use this method.
* @param pkg packageName
* @param name the name of the {@link JavaFileObject}
* @param URI uri of the {@link JavaFileObject}, if null the relative URI
* in the form binaryName.extension is generated.
* @param lastModified mtime of the virtual file
* @param content the content of the {@link JavaFileObject}
* @return {@link JavaFileObject}, never returns null
*/
public static PrefetchableJavaFileObject memoryFileObject(final CharSequence pkg, final CharSequence name,
final URI uri, final long lastModified, final CharSequence content) {
Parameters.notNull("pkg", pkg);
Parameters.notNull("name", name);
Parameters.notNull("content", content);
final String pkgStr = (pkg instanceof String) ? (String) pkg : pkg.toString();
final String nameStr = (name instanceof String) ? (String) name : name.toString();
int length = content.length();
if ( length != 0 && Character.isWhitespace( content.charAt( length - 1 ) ) ) {
return new MemoryFileObject(pkgStr, nameStr, uri, lastModified, CharBuffer.wrap( content ) );
}
else {
return new MemoryFileObject(pkgStr, nameStr, uri, lastModified, (CharBuffer)CharBuffer.allocate( length + 1 ).append( content ).append( ' ' ).flip() );
}
}
示例4: decodePassword
import java.nio.CharBuffer; //導入方法依賴的package包/類
static String decodePassword(byte[] bytes) throws CharacterCodingException {
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder(); // NOI18N
ByteBuffer input = ByteBuffer.wrap(bytes);
int outputLength = (int)(bytes.length * (double)decoder.maxCharsPerByte());
if (outputLength == 0) {
return ""; // NOI18N
}
char[] chars = new char[outputLength];
CharBuffer output = CharBuffer.wrap(chars);
CoderResult result = decoder.decode(input, output, true);
if (!result.isError() && !result.isOverflow()) {
result = decoder.flush(output);
}
if (result.isError() || result.isOverflow()) {
throw new CharacterCodingException();
} else {
return new String(chars, 0, output.position());
}
}
示例5: toString
import java.nio.CharBuffer; //導入方法依賴的package包/類
String toString(byte[] ba, int length) {
CharsetDecoder cd = decoder().reset();
int len = (int)(length * cd.maxCharsPerByte());
char[] ca = new char[len];
if (len == 0)
return new String(ca);
ByteBuffer bb = ByteBuffer.wrap(ba, 0, length);
CharBuffer cb = CharBuffer.wrap(ca);
CoderResult cr = cd.decode(bb, cb, true);
if (!cr.isUnderflow())
throw new IllegalArgumentException(cr.toString());
cr = cd.flush(cb);
if (!cr.isUnderflow())
throw new IllegalArgumentException(cr.toString());
return new String(ca, 0, cb.position());
}
示例6: getSubstringByte
import java.nio.CharBuffer; //導入方法依賴的package包/類
/**
* 指定したバイト數で文字列をカットする
*
* @param obj 対象オブジェクト
* @param capacity カットするバイト數
* @return String
* @throws CharacterCodingException
* @throws UnsupportedEncodingException
*/
private String getSubstringByte(final Object obj, final int capacity) throws CharacterCodingException,
UnsupportedEncodingException {
String str = obj == null ? "null" : obj.toString();
if (capacity < 1) {
return str;
}
CharsetEncoder ce = Charset.forName(ENCODING_SHIFT_JIS).newEncoder()
.onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE).reset();
if (capacity >= ce.maxBytesPerChar() * str.length()) {
return str;
}
CharBuffer cb = CharBuffer.wrap(new char[Math.min(str.length(), capacity)]);
str.getChars(0, Math.min(str.length(), cb.length()), cb.array(), 0);
if (capacity >= ce.maxBytesPerChar() * cb.limit()) {
return cb.toString();
}
ByteBuffer out = ByteBuffer.allocate(capacity);
ce.reset();
CoderResult cr = null;
if (cb.hasRemaining()) {
cr = ce.encode(cb, out, true);
} else {
cr = CoderResult.UNDERFLOW;
}
if (cr.isUnderflow()) {
cr = ce.flush(out);
}
return cb.flip().toString();
}
示例7: onCharReceived
import java.nio.CharBuffer; //導入方法依賴的package包/類
@Override
protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException {
try {
char[] charArray = new char[buf.remaining()];
System.arraycopy(buf.array(), 0, charArray, 0, buf.remaining());
CharBuffer charBuffer = CharBuffer.wrap(charArray);
ParseStream.blockingQueue.put(new AbstractMap.SimpleEntry<String, CharBuffer>(clientUri, charBuffer));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
示例8: getCharContent
import java.nio.CharBuffer; //導入方法依賴的package包/類
@Override
@NonNull
public final CharBuffer getCharContent(final boolean ignoreEncodingErrors) throws IOException {
String _text = this.text;
if (_text == null) {
_text = getContent(false);
}
return CharBuffer.wrap(_text);
}
示例9: doParse
import java.nio.CharBuffer; //導入方法依賴的package包/類
private static <T extends Tree> T doParse(JavacTaskImpl task, String text, SourcePositions[] sourcePositions, int offset, Function<Parser, T> actualParse) {
if (text == null || (sourcePositions != null && sourcePositions.length != 1))
throw new IllegalArgumentException();
//use a working init order:
com.sun.tools.javac.main.JavaCompiler.instance(task.getContext());
com.sun.tools.javac.tree.TreeMaker jcMaker = com.sun.tools.javac.tree.TreeMaker.instance(task.getContext());
int oldPos = jcMaker.pos;
try {
//from org/netbeans/modules/java/hints/spiimpl/Utilities.java:
Context context = task.getContext();
JavaCompiler compiler = JavaCompiler.instance(context);
JavaFileObject prev = compiler.log.useSource(new DummyJFO());
Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(compiler.log) {
@Override
public void report(JCDiagnostic diag) {
//ignore:
}
};
try {
CharBuffer buf = CharBuffer.wrap((text+"\u0000").toCharArray(), 0, text.length());
ParserFactory factory = ParserFactory.instance(context);
Parser parser = factory.newParser(buf, false, true, false, false);
if (parser instanceof JavacParser) {
if (sourcePositions != null)
sourcePositions[0] = new ParserSourcePositions((JavacParser)parser, offset);
return actualParse.apply(parser);
}
return null;
} finally {
compiler.log.useSource(prev);
compiler.log.popDiagnosticHandler(discardHandler);
}
} finally {
jcMaker.pos = oldPos;
}
}
示例10: reward
import java.nio.CharBuffer; //導入方法依賴的package包/類
private synchronized void reward() {
length++;
try {
CharBuffer response = CharBuffer.wrap("{'type': 'kill'}");
outbound.writeTextMessage(response);
} catch (IOException ioe) {
// Ignore
}
}
示例11: toBytes
import java.nio.CharBuffer; //導入方法依賴的package包/類
/**
* Converts char array to byte array securely
*
* @param chars the char array which will be converted to byte array
* @return the byte array
*/
@NonNull
private byte[] toBytes(@NonNull char[] chars) {
CharBuffer charBuffer = CharBuffer.wrap(chars);
ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
byte[] bytes = Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit());
Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data
Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
return bytes;
}
示例12: decode
import java.nio.CharBuffer; //導入方法依賴的package包/類
private char decode(byte byte1, byte byte2, byte shiftFlag)
{
byte1 |= MSB;
byte2 |= MSB;
byte[] tmpByte = { byte1,byte2 };
char[] tmpChar = new char[1];
int i = 0,
tmpIndex = 0;
switch(shiftFlag) {
case SOFlag:
tmpIndex = curSODes;
tmpDecoder = SODecoder;
break;
case SS2Flag:
tmpIndex = curSS2Des;
tmpDecoder = SS2Decoder;
break;
case SS3Flag:
tmpIndex = curSS3Des;
tmpDecoder = SS3Decoder;
break;
}
if (tmpDecoder != null) {
for(i = 0; i < tmpDecoder.length; i++) {
if(tmpIndex == i) {
try {
ByteBuffer bb = ByteBuffer.wrap(tmpByte,0,2);
CharBuffer cc = CharBuffer.wrap(tmpChar,0,1);
tmpDecoder[i].decode(bb, cc, true);
cc.flip();
return cc.get();
} catch (Exception e) {}
}
}
}
return REPLACE_CHAR;
}
示例13: charToUtf16
import java.nio.CharBuffer; //導入方法依賴的package包/類
static byte[] charToUtf16(char[] chars) {
Charset utf8 = Charset.forName("UTF-16LE");
CharBuffer cb = CharBuffer.wrap(chars);
ByteBuffer bb = utf8.encode(cb);
int len = bb.limit();
byte[] answer = new byte[len];
bb.get(answer, 0, len);
return answer;
}
示例14: encode
import java.nio.CharBuffer; //導入方法依賴的package包/類
static byte[] encode(Charset cs, byte coder, byte[] val) {
if (cs == UTF_8) {
return encodeUTF8(coder, val);
} else if (cs == ISO_8859_1) {
return encode8859_1(coder, val);
} else if (cs == US_ASCII) {
return encodeASCII(coder, val);
}
CharsetEncoder ce = cs.newEncoder();
// fastpath for ascii compatible
if (coder == LATIN1 && (((ce instanceof ArrayEncoder) &&
((ArrayEncoder)ce).isASCIICompatible() &&
!hasNegatives(val, 0, val.length)))) {
return Arrays.copyOf(val, val.length);
}
int len = val.length >> coder; // assume LATIN1=0/UTF16=1;
int en = scale(len, ce.maxBytesPerChar());
byte[] ba = new byte[en];
if (len == 0) {
return ba;
}
boolean isTrusted = cs.getClass().getClassLoader0() == null ||
System.getSecurityManager() == null;
ce.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE)
.reset();
if (ce instanceof ArrayEncoder) {
if (!isTrusted) {
val = Arrays.copyOf(val, val.length);
}
int blen = (coder == LATIN1 ) ? ((ArrayEncoder)ce).encodeFromLatin1(val, 0, len, ba)
: ((ArrayEncoder)ce).encodeFromUTF16(val, 0, len, ba);
if (blen != -1) {
return safeTrim(ba, blen, isTrusted);
}
}
char[] ca = (coder == LATIN1 ) ? StringLatin1.toChars(val)
: StringUTF16.toChars(val);
ByteBuffer bb = ByteBuffer.wrap(ba);
CharBuffer cb = CharBuffer.wrap(ca, 0, len);
try {
CoderResult cr = ce.encode(cb, bb, true);
if (!cr.isUnderflow())
cr.throwException();
cr = ce.flush(bb);
if (!cr.isUnderflow())
cr.throwException();
} catch (CharacterCodingException x) {
throw new Error(x);
}
return safeTrim(ba, bb.position(), isTrusted);
}
示例15: convert
import java.nio.CharBuffer; //導入方法依賴的package包/類
/**
* Convert the given characters to bytes.
*
* @param cc char input
* @param bc byte output
*/
public void convert(CharChunk cc, ByteChunk bc)
throws IOException {
if ((bb == null) || (bb.array() != bc.getBuffer())) {
// Create a new byte buffer if anything changed
bb = ByteBuffer.wrap(bc.getBuffer(), bc.getEnd(),
bc.getBuffer().length - bc.getEnd());
} else {
// Initialize the byte buffer
bb.limit(bc.getBuffer().length);
bb.position(bc.getEnd());
}
if ((cb == null) || (cb.array() != cc.getBuffer())) {
// Create a new char buffer if anything changed
cb = CharBuffer.wrap(cc.getBuffer(), cc.getStart(),
cc.getLength());
} else {
// Initialize the char buffer
cb.limit(cc.getEnd());
cb.position(cc.getStart());
}
CoderResult result = null;
// Parse leftover if any are present
if (leftovers.position() > 0) {
int pos = bb.position();
// Loop until one char is encoded or there is a encoder error
do {
leftovers.put((char) cc.substract());
leftovers.flip();
result = encoder.encode(leftovers, bb, false);
leftovers.position(leftovers.limit());
leftovers.limit(leftovers.array().length);
} while (result.isUnderflow() && (bb.position() == pos));
if (result.isError() || result.isMalformed()) {
result.throwException();
}
cb.position(cc.getStart());
leftovers.position(0);
}
// Do the decoding and get the results into the byte chunk and the char
// chunk
result = encoder.encode(cb, bb, false);
if (result.isError() || result.isMalformed()) {
result.throwException();
} else if (result.isOverflow()) {
// Propagate current positions to the byte chunk and char chunk
bc.setEnd(bb.position());
cc.setOffset(cb.position());
} else if (result.isUnderflow()) {
// Propagate current positions to the byte chunk and char chunk
bc.setEnd(bb.position());
cc.setOffset(cb.position());
// Put leftovers in the leftovers char buffer
if (cc.getLength() > 0) {
leftovers.limit(leftovers.array().length);
leftovers.position(cc.getLength());
cc.substract(leftovers.array(), 0, cc.getLength());
}
}
}