package common.util.encoding;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
public class EString {
private String newString;
public EString(String str, String old_encoding, String encoding)
throws UnsupportedEncodingException {
ByteBuffer buff = ByteBuffer
.allocate(str.getBytes(old_encoding).length);
buff.put(str.getBytes(old_encoding));
//ready to get
buff.flip();
buff.rewind();
Charset decoder = Charset.forName(old_encoding);
Charset encoder = Charset.forName(encoding);
CharBuffer cb = decoder.decode(buff);
ByteBuffer result_buff = encoder.encode(cb);
try {
newString = new String(result_buff.array(), encoding);
// cut overflow blank str
newString = newString.substring(0, str.length());
} catch (UnsupportedEncodingException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
@Override
public String toString() {
return newString;
}
}
自己实现的JAVA转码工具类
最新推荐文章于 2024-03-18 15:40:43 发布
本文介绍了一个名为EString的Java类,该类用于实现字符串在不同字符集之间的转换。通过使用ByteBuffer和Charset进行编码和解码,确保了从旧编码到新编码的平滑过渡。
201

被折叠的 条评论
为什么被折叠?



