import java.io.UnsupportedEncodingException;
public class HanUtf8 {
public static void main(String[] args) {
if (args == null || args.length == 0) {
System.out.println("Input with format:\ncommand \\xAE\\xEC\\x9c... or command 汉字。。。");
return;
}
if (args[0].contains("x")) {
System.out.println(code2han(args[0]));
} else {
System.out.println(han2code(args[0]));
}
}
public static String code2han(String code) {
String[] codeArr = code.split("\\\\x");
byte[] bArr = new byte[codeArr.length-1];
for(int i=1; i<codeArr.length; i++){
int n = Integer.parseInt(codeArr[i], 16);
byte b = new Integer(n).byteValue();
bArr[i-1] = b;
}
try {
return new String(bArr, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
}
public static String han2code(String str) {
byte[] bArr = str.getBytes();
String rtn = "";
for (byte b : bArr) {
rtn += "\\x" + Integer.toHexString(b & 0xFF);
}
return rtn;
}
}