Java 输出指定编码的字符串

时间:2023-03-08 20:47:24
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

下面代码为转换的函数:

 /***
* 按照指定编码转换字符串
* @param str 需要转换的字符串
* @param srcEncode 传递过来的字符串编码格式
* @param dstEncode 需要转换成的编码格式
* @return 指定编码格式的字符串
*/
public String translate(String str, String srcEncode,String dstEncode) {
String tempStr = "";
try {
tempStr = new String(str.getBytes(srcEncode),dstEncode);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tempStr;
}