自己实现的JAVA转码工具类


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)