JAVA中encoder_Java CharsetEncoder encode(CharBuffer in)用法及代码示例

encode(CharBuffer input)方法是java.nio.charset.CharsetEncoder的内置方法,该方法将单个输入字符缓冲区的剩余内容编码为newly-allocated byte-buffer。它的leaf中的encode()方法实现了整个编码操作。如果正在进行操作,则不应调用此函数。

用法:

public final ByteBuffer encode(CharBuffer input)

参数:该函数接受指定输入字符缓冲区的强制参数输入。

返回值:该函数返回一个newly-allocated字节缓冲区,其中包含编码操作的结果。

错误和异常:该函数引发四个异常,如下所示:

IllegalStateException:如果已经在进行编码操作,则抛出该错误。

格式错误的输入异常:如果从输入缓冲区的当前位置开始的字符序列不是合法的16位Unicode序列,并且当前的malformed-input操作为CodingErrorAction.REPORT,则抛出该错误。

UnmappableCharacterException:如果无法将从输入缓冲区的当前位置开始的字符序列映射到等效的字节序列,并且当前的unmappable-character操作为CodingErrorAction.REPORT,则会抛出该错误:

CharacterCodingException

下面是上述功能的实现:

程序1:

// Java program to implement

// the above function

import java.nio.CharBuffer;

import java.nio.charset.Charset;

import java.nio.charset.CharsetEncoder;

public class Main {

public static void main(String[] args) throws Exception

{

// Gets the new encoder

CharsetEncoder encoder = Charset.forName("UTF8").newEncoder();

// Encodes

String res = "gfggfg";

System.out.println(encoder.encode(CharBuffer.wrap(res)));

}

}

输出:

java.nio.HeapByteBuffer[pos=0 lim=6 cap=6]

程序2:

// Java program to implement

// the above function

import java.nio.CharBuffer;

import java.nio.charset.Charset;

import java.nio.charset.CharsetEncoder;

public class Main {

public static void main(String[] args) throws Exception

{

// Gets the new encoder

CharsetEncoder encoder = Charset.forName("UTF16").newEncoder();

// Encodes

String res = "gopal";

System.out.println(encoder.encode(CharBuffer.wrap(res)));

}

}

输出:

java.nio.HeapByteBuffer[pos=0 lim=12 cap=21]

异常程序无法在程序中演示。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值