Java 输出指定编码的字符串

Java Sting类有个根据byte,字符编码来输出的构造函数。
以下为java文档中的解释。

public String(byte[] bytes, String charsetName) throws UnsupportedEncodingException
Constructs a new   String  by decoding the specified array of bytes using the specified charset. The length of the new   String  is a function of the charset, and hence may not be equal to the length of the byte array.

The behavior of this constructor when the given bytes are not valid in the given charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.

 

Parameters:
bytes  - the bytes to be decoded into characters
charsetName  - the name of a supported   charset
Throws:
UnsupportedEncodingException  - If the named charset is not supported
Since:
JDK1.1

下面代码为转换的函数:

 1 /***
 2  * 按照指定编码转换字符串
 3  * @param str 需要转换的字符串
 4  * @param srcEncode 传递过来的字符串编码格式
 5  * @param dstEncode 需要转换成的编码格式
 6  * @return 指定编码格式的字符串
 7  */
 8 public String translate(String str, String srcEncode,String dstEncode) {
 9     String tempStr = "";
10     try {
11         tempStr = new String(str.getBytes(srcEncode),dstEncode);
12     } catch (UnsupportedEncodingException e) {
13         // TODO Auto-generated catch block
14         e.printStackTrace();
15     }
16     return tempStr;
17 }

 

转载于:https://www.cnblogs.com/tianyaxue/p/3145099.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值