本文整理汇总了Java中java.nio.charset.CharsetEncoder类的典型用法代码示例。如果您正苦于以下问题:Java CharsetEncoder类的具体用法?Java CharsetEncoder怎么用?Java CharsetEncoder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CharsetEncoder类属于java.nio.charset包,在下文中一共展示了CharsetEncoder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: newFixedLengthResponse
import java.nio.charset.CharsetEncoder; //导入依赖的package包/类
/**
* Create a text response with known length.
*/
public static Response newFixedLengthResponse(IStatus status, String mimeType, String txt) {
ContentType contentType = new ContentType(mimeType);
if (txt == null) {
return newFixedLengthResponse(status, mimeType, new ByteArrayInputStream(new byte[0]), 0);
} else {
byte[] bytes;
try {
CharsetEncoder newEncoder = Charset.forName(contentType.getEncoding()).newEncoder();
if (!newEncoder.canEncode(txt)) {
contentType = contentType.tryUTF8();
}
bytes = txt.getBytes(contentType.getEncoding());
} catch (UnsupportedEncodingException e) {
NanoHTTPD.LOG.log(Level.SEVERE, "encoding problem, responding nothing", e);
bytes = new byte[0];
}
return newFixedLengthResponse(status, contentType.getContentTypeHeader(), new ByteArrayInputStream(bytes), bytes.length);
}
}
示例2: 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();
}
示例3: 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;
}
示例4: openSource
import java.nio.charset.CharsetEncoder; //导入依赖的package包/类
/**
* Called by CodeModel to store the specified file.
* The callee must allocate a storage to store the specified file.
*
* <p>
* The returned stream will be closed before the next file is
* stored. So the callee can assume that only one OutputStream
* is active at any given time.
*
* @param pkg
* The package of the file to be written.
* @param fileName
* File name without the path. Something like
* "Foo.java" or "Bar.properties"
*/
public Writer openSource( JPackage pkg, String fileName ) throws IOException {
final OutputStreamWriter bw = encoding != null
? new OutputStreamWriter(openBinary(pkg,fileName), encoding)
: new OutputStreamWriter(openBinary(pkg,fileName));
// create writer
try {
return new UnicodeEscapeWriter(bw) {
// can't change this signature to Encoder because
// we can't have Encoder in method signature
private final CharsetEncoder encoder = EncoderFactory.createEncoder(bw.getEncoding());
@Override
protected boolean requireEscaping(int ch) {
// control characters
if( ch<0x20 && " \t\r\n".indexOf(ch)==-1 ) return true;
// check ASCII chars, for better performance
if( ch<0x80 ) return false;
return !encoder.canEncode((char)ch);
}
};
} catch( Throwable t ) {
return new UnicodeEscapeWriter(bw);
}
}
示例5: getBytes
import java.nio.charset.CharsetEncoder; //导入依赖的package包/类
/**
* Returns a new byte array containing the characters of the specified
* string encoded using the given charset.
*
* It is equivalent to <code>input.getBytes(charset)</code> except it has
* workaround for the bug ID 61917.
*
* @see https://code.google.com/p/android/issues/detail?id=61917
*/
//@formatter:off
/*
* The original code is available from
* https://android.googlesource.com/platform/libcore/+/master/libdvm/src/main/java/java/lang/String.java
*/
//@formatter:on
public static byte[] getBytes(String input, Charset charset) {
CharBuffer chars = CharBuffer.wrap(input.toCharArray());
// @formatter:off
CharsetEncoder encoder = charset.newEncoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
// @formatter:on
ByteBuffer buffer;
buffer = encode(chars.asReadOnlyBuffer(), encoder);
byte[] bytes = new byte[buffer.limit()];
buffer.get(bytes);
return bytes;
}
示例6: encodeProperties
import java.nio.charset.CharsetEncoder; //导入依赖的package包/类
private IoBuffer encodeProperties ( final IoSession session, final Map<String, String> properties ) throws CharacterCodingException
{
final IoBuffer data = IoBuffer.allocate ( 0 );
data.setAutoExpand ( true );
data.putInt ( properties.size () );
final CharsetEncoder encoder = getCharsetEncoder ( session );
for ( final Map.Entry<String, String> entry : properties.entrySet () )
{
final String key = entry.getKey ();
final String value = entry.getValue ();
data.putString ( key, encoder );
data.put ( (byte)0x00 );
data.putString ( value, encoder );
data.put ( (byte)0x00 );
}
data.flip ();
return data;
}
示例7: encodeProperties
import java.nio.charset.CharsetEncoder; //导入依赖的package包/类
private void encodeProperties ( final IoBuffer data, final Map<String, String> properties ) throws ProtocolCodecException
{
final CharsetEncoder encoder = this.defaultCharset.newEncoder ();
data.putUnsignedShort ( properties.size () );
for ( final Map.Entry<String, String> entry : properties.entrySet () )
{
try
{
data.putPrefixedString ( entry.getKey (), encoder );
data.putPrefixedString ( entry.getValue (), encoder );
}
catch ( final CharacterCodingException e )
{
throw new ProtocolCodecException ( e );
}
}
}
示例8: 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();
}
示例9: DefaultManagedHttpClientConnection
import java.nio.charset.CharsetEncoder; //导入依赖的package包/类
public DefaultManagedHttpClientConnection(
final String id,
final int buffersize,
final int fragmentSizeHint,
final CharsetDecoder chardecoder,
final CharsetEncoder charencoder,
final MessageConstraints constraints,
final ContentLengthStrategy incomingContentStrategy,
final ContentLengthStrategy outgoingContentStrategy,
final HttpMessageWriterFactory<HttpRequest> requestWriterFactory,
final HttpMessageParserFactory<HttpResponse> responseParserFactory) {
super(buffersize, fragmentSizeHint, chardecoder, charencoder,
constraints, incomingContentStrategy, outgoingContentStrategy,
requestWriterFactory, responseParserFactory);
this.id = id;
this.attributes = new ConcurrentHashMap<String, Object>();
}
示例10: test_error_0
import java.nio.charset.CharsetEncoder; //导入依赖的package包/类
public void test_error_0() throws Exception {
Charset charset = Charset.forName("UTF-8");
CharsetEncoder charsetEncoder = new MockCharsetEncoder2(charset);
Exception error = null;
char[] chars = "abc".toCharArray();
try {
encode(charsetEncoder, chars, 0, chars.length);
} catch (Exception ex) {
error = ex;
}
Assert.assertNotNull(error);
}
示例11: SessionOutputBufferImpl
import java.nio.charset.CharsetEncoder; //导入依赖的package包/类
/**
* Creates new instance of SessionOutputBufferImpl.
*
* @param metrics HTTP transport metrics.
* @param buffersize buffer size. Must be a positive number.
* @param fragementSizeHint fragment size hint defining a minimal size of a fragment
* that should be written out directly to the socket bypassing the session buffer.
* Value {@code 0} disables fragment buffering.
* @param charencoder charencoder to be used for encoding HTTP protocol elements.
* If {@code null} simple type cast will be used for char to byte conversion.
*/
public SessionOutputBufferImpl(
final HttpTransportMetricsImpl metrics,
final int buffersize,
final int fragementSizeHint,
final CharsetEncoder charencoder) {
super();
Args.positive(buffersize, "Buffer size");
Args.notNull(metrics, "HTTP transport metrcis");
this.metrics = metrics;
this.buffer = new ByteArrayBuffer(buffersize);
this.fragementSizeHint = fragementSizeHint >= 0 ? fragementSizeHint : 0;
this.encoder = charencoder;
}
示例12: 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);
}
}
示例13: canEncode
import java.nio.charset.CharsetEncoder; //导入依赖的package包/类
/**
* Check if encode can handle the chars in this string.
*
*/
protected boolean canEncode(String s) {
final CharsetEncoder encoder =
Charset.forName(System.getProperty("file.encoding")).newEncoder();
char[] chars = s.toCharArray();
for (int i=0; i<chars.length; i++) {
if(!encoder.canEncode(chars[i])) {
return false;
}
}
return true;
}
示例14: newEncoder
import java.nio.charset.CharsetEncoder; //导入依赖的package包/类
public CharsetEncoder newEncoder() {
// Need to force the replacement byte to 0x3f
// because JIS_X_0208_Encoder defines its own
// alternative 2 byte substitution to permit it
// to exist as a self-standing Encoder
byte[] replacementBytes = { (byte)0x3f };
return new Encoder(this).replaceWith(replacementBytes);
}
示例15: getCharsetEncoder
import java.nio.charset.CharsetEncoder; //导入依赖的package包/类
public static CharsetEncoder getCharsetEncoder ( final IoSession session )
{
final Object charset = session.getAttribute ( ATTR_CHARSET, Charset.forName ( DEFAULT_CHARSET_NAME ) );
if ( charset instanceof Charset )
{
return ( (Charset)charset ).newEncoder ();
}
else
{
return Charset.forName ( DEFAULT_CHARSET_NAME ).newEncoder ();
}
}