本文整理匯總了Java中java.nio.charset.CharsetEncoder.encode方法的典型用法代碼示例。如果您正苦於以下問題:Java CharsetEncoder.encode方法的具體用法?Java CharsetEncoder.encode怎麽用?Java CharsetEncoder.encode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.nio.charset.CharsetEncoder
的用法示例。
在下文中一共展示了CharsetEncoder.encode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: getBytes
import java.nio.charset.CharsetEncoder; //導入方法依賴的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());
}
示例2: encode
import java.nio.charset.CharsetEncoder; //導入方法依賴的package包/類
/**
* Converts the provided String to bytes using the
* UTF-8 encoding. If <code>replace</code> is true, then
* malformed input is replaced with the
* substitution character, which is U+FFFD. Otherwise the
* method throws a MalformedInputException.
* @return ByteBuffer: bytes stores at ByteBuffer.array()
* and length is ByteBuffer.limit()
*/
public static ByteBuffer encode(String string, boolean replace)
throws CharacterCodingException {
CharsetEncoder encoder = ENCODER_FACTORY.get();
if (replace) {
encoder.onMalformedInput(CodingErrorAction.REPLACE);
encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
}
ByteBuffer bytes =
encoder.encode(CharBuffer.wrap(string.toCharArray()));
if (replace) {
encoder.onMalformedInput(CodingErrorAction.REPORT);
encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
}
return bytes;
}
示例3: doWriteText
import java.nio.charset.CharsetEncoder; //導入方法依賴的package包/類
private void doWriteText(CharBuffer buffer, boolean finalFragment)
throws IOException {
CharsetEncoder encoder = B2CConverter.UTF_8.newEncoder();
do {
CoderResult cr = encoder.encode(buffer, bb, true);
if (cr.isError()) {
cr.throwException();
}
bb.flip();
if (buffer.hasRemaining()) {
doWriteBytes(bb, false);
} else {
doWriteBytes(bb, finalFragment);
}
} while (buffer.hasRemaining());
// Reset - bb will be cleared in doWriteBytes()
cb.clear();
}
示例4: doWriteText
import java.nio.charset.CharsetEncoder; //導入方法依賴的package包/類
private void doWriteText(CharBuffer buffer, boolean finalFragment) throws IOException {
CharsetEncoder encoder = B2CConverter.UTF_8.newEncoder();
do {
CoderResult cr = encoder.encode(buffer, bb, true);
if (cr.isError()) {
cr.throwException();
}
bb.flip();
if (buffer.hasRemaining()) {
doWriteBytes(bb, false);
} else {
doWriteBytes(bb, finalFragment);
}
} while (buffer.hasRemaining());
// Reset - bb will be cleared in doWriteBytes()
cb.clear();
}
示例5: byCharsetEncoder_US_ASCII
import java.nio.charset.CharsetEncoder; //導入方法依賴的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);
}
}
示例6: fromString
import java.nio.charset.CharsetEncoder; //導入方法依賴的package包/類
public ByteBuffer fromString(String source)
{
// the encoder must be reset each time it's used, hence the thread-local storage
CharsetEncoder theEncoder = encoder.get();
theEncoder.reset();
try
{
return theEncoder.encode(CharBuffer.wrap(source));
}
catch (CharacterCodingException exc)
{
throw new MarshalException(String.format("Invalid ASCII character in string literal: %s", exc));
}
}
示例7: appendBytes
import java.nio.charset.CharsetEncoder; //導入方法依賴的package包/類
private static void appendBytes(ByteStringBuilder builder, CharsetEncoder encoder,
int codePoint) {
final ByteBuffer bytes;
try {
bytes = encoder.encode(CharBuffer.wrap(Character.toChars(codePoint)));
} catch (CharacterCodingException ex) {
// should not happen
throw new IllegalStateException(ex);
}
while (bytes.hasRemaining()) {
builder.append(bytes.get());
}
}
示例8: testRoundTrip
import java.nio.charset.CharsetEncoder; //導入方法依賴的package包/類
@Test
public void testRoundTrip() throws CharacterCodingException {
final CharsetDecoder dec = charset.newDecoder();
final CharsetEncoder enc = charset.newEncoder();
final byte[] b1 = new byte[256];
for (int i = 0; i < b1.length; i++)
b1[i] = (byte) i;
final ByteBuffer bb1 = ByteBuffer.wrap(b1);
final CharBuffer cb = dec.decode(bb1);
final ByteBuffer bb2 = enc.encode(cb);
final byte[] b2 = bb2.array();
assertTrue(Arrays.equals(b1, b2));
}
示例9: encode
import java.nio.charset.CharsetEncoder; //導入方法依賴的package包/類
private ByteBuffer encode(String str)
{
// Encode a string into a byte buffer
ByteBuffer bb = null;
CharsetEncoder isoencoder = charset.newEncoder();
try {
bb = isoencoder.encode(CharBuffer.wrap(str));
} catch (CharacterCodingException e) {
log.error(e);
}
return bb;
}
示例10: encode
import java.nio.charset.CharsetEncoder; //導入方法依賴的package包/類
static byte[] encode(Charset cs, char[] ca, int off, int len) {
CharsetEncoder ce = cs.newEncoder();
int en = scale(len, ce.maxBytesPerChar());
byte[] ba = new byte[en];
if (len == 0)
return ba;
boolean isTrusted = false;
if (System.getSecurityManager() != null) {
if (!(isTrusted = (cs.getClass().getClassLoader0() == null))) {
ca = Arrays.copyOfRange(ca, off, off + len);
off = 0;
}
}
ce.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE)
.reset();
if (ce instanceof ArrayEncoder) {
int blen = ((ArrayEncoder)ce).encode(ca, off, len, ba);
return safeTrim(ba, blen, cs, isTrusted);
} else {
ByteBuffer bb = ByteBuffer.wrap(ba);
CharBuffer cb = CharBuffer.wrap(ca, off, 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(), cs, isTrusted);
}
}
示例11: write
import java.nio.charset.CharsetEncoder; //導入方法依賴的package包/類
@Override
public void write(DataOutput out) throws IOException {
out.writeByte(0);
Map<String,String> writeHeaders = getHeaders();
if (null != writeHeaders) {
out.writeInt(headers.size());
CharsetEncoder encoder = ENCODER_FACTORY.get();
for (String key : headers.keySet()) {
out.writeByte(EVENT_MAP_TEXT_WRITABLE_ID);
ByteBuffer keyBytes = encoder.encode(CharBuffer.wrap(key.toCharArray()));
int keyLength = keyBytes.limit();
WritableUtils.writeVInt(out, keyLength);
out.write(keyBytes.array(), 0, keyLength);
String value = headers.get(key);
out.write(EVENT_MAP_TEXT_WRITABLE_ID);
ByteBuffer valueBytes = encoder.encode(CharBuffer.wrap(value.toCharArray()));
int valueLength = valueBytes.limit();
WritableUtils.writeVInt(out, valueLength );
out.write(valueBytes.array(), 0, valueLength);
}
} else {
out.writeInt( 0 );
}
byte[] body = getBody();
if (body == null) {
out.writeInt(-1);
} else {
out.writeInt(body.length);
out.write(body);
}
}
示例12: encode
import java.nio.charset.CharsetEncoder; //導入方法依賴的package包/類
public static byte[] encode (final char[] charArray){
try {
final CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
final ByteBuffer bb = encoder.encode(CharBuffer.wrap(charArray));
final byte[] ba=new byte[bb.limit()];
bb.get(ba);
return ba;
} catch (CharacterCodingException ex) {
STRINGUTIL_LOGGER.error("Sorry. had a error on during string encode. ("+ex.toString()+")");
return null;
}
}
示例13: getBytes
import java.nio.charset.CharsetEncoder; //導入方法依賴的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;
// UTF-8 only for now. Other ArrayDeocder only handles
// CodingErrorAction.REPLACE mode.
if (isUTF8 && ce instanceof ArrayEncoder) {
int blen = ((ArrayEncoder)ce).encode(ca, 0, ca.length, ba);
if (blen == -1) // malformed
throw new IllegalArgumentException("MALFORMED");
return Arrays.copyOf(ba, blen);
}
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());
}
示例14: getSubstringByte
import java.nio.charset.CharsetEncoder; //導入方法依賴的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();
}
示例15: encode
import java.nio.charset.CharsetEncoder; //導入方法依賴的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);
}