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


Java CharsetEncoder类代码示例

本文整理汇总了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);
    }
}
 
开发者ID:Webtrekk,项目名称:webtrekk-android-sdk,代码行数:23,代码来源:NanoHTTPD.java

示例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();
}
 
开发者ID:how2j,项目名称:lazycat,代码行数:19,代码来源:WsOutbound.java

示例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;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:25,代码来源:Text.java

示例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);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:41,代码来源:CodeWriter.java

示例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;

}
 
开发者ID:Xiangxingqian,项目名称:WeiXinGroupSend,代码行数:30,代码来源:Utf7ImeHelper.java

示例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;
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:25,代码来源:MessageChannelCodecFilter.java

示例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 );
        }
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:19,代码来源:ProtocolEncoderImpl.java

示例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();
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:20,代码来源:WsOutbound.java

示例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>();
}
 
开发者ID:mozilla-mobile,项目名称:FirefoxData-android,代码行数:18,代码来源:DefaultManagedHttpClientConnection.java

示例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);
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:15,代码来源:SerialWriterStringEncoderTest2.java

示例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;
}
 
开发者ID:gusavila92,项目名称:java-android-websocket-client,代码行数:25,代码来源:SessionOutputBufferImpl.java

示例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);
    }
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:36,代码来源:StringCoding.java

示例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;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:16,代码来源:IndentingWriter.java

示例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);
    }
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:11,代码来源:PCK_OLD.java

示例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 ();
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:13,代码来源:Sessions.java


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