[英]How to convert between UTF-8 and native String in Java?
就像图片一样,我想在Java中的编码UTF-8字符串和本机字符串之间进行转换。 有人会建议吗? 非常感谢!
ps。 例如,
String a = "这是一个例子,this is a example";
String b = null;
// block A: processing a, and let b = "这是一个例子,this is a example"
如何实现“区块A”?
Apache Commons Lang StringEscapeUtils.unescapeXml(...)
是您想要的。 根据原始字符串的来源,HTML变体之一可能更合适。
像这样使用:
String a = "这是一个例子,this is a example";
String b = StringEscapeUtils.unescapeXml(a);
// block A: processing a, and let b = "这是一个例子,this is a example"
System.out.println(a);
System.out.println(b);
输出:
这是一个例子,this is a example
这是一个例子,this is a example
也有转换其他方法的方法。
您可以使用Charset。 请参阅此处的文档
Charset.forName("UTF-8").encode(text)
要么
您还可以使用“ java.lang.String”类的getBytes()
方法
text.getBytes(Charset.forName("UTF-8"));
说明文件:
public byte [] getBytes(Charset charset)
使用给定的字符集将此String编码为字节序列,并将结果存储到新的字节数组中。此方法始终使用此字符集的默认替换字节数组替换格式错误的输入和不可映射的字符序列。 当需要对编码过程进行更多控制时,应使用CharsetEncoder类。
参数: charset-用于编码字符串的字符集
返回:结果字节数组
以来:
1.6
右边是十六进制数字HTML实体。
现在,apache commons库具有一个StringEscapeUtils,可以将其从 StringEscapeUtils转换为String,但是相反的情况并不明显(应尝试=,可能会提供命名实体)。
public static void main(String[] args) throws InterruptedException {
String a = "这是一个例子,this is a example";
String b = fromHtmlEntities(a);
System.out.println(b);
String a2 = toHtmlEntities(b);
System.out.println(a2.equals(a));
System.out.println(a);
System.out.println(a2);
}
public static String fromHtmlEntities(String s) {
Pattern numericEntityPattern = Pattern.compile("\\&#[Xx]([0-9A-Fa-f]{1,6});");
Matcher m = numericEntityPattern.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()) {
int codePoint = Integer.parseInt(m.group(1), 16);
String replacement = new String(new int[] { codePoint }, 0, 1);
m.appendReplacement(sb, replacement);
}
m.appendTail(sb);
return sb.toString();
}
// Uses java 8
public static String toHtmlEntities(String s) {
int[] codePoints = s.codePoints().flatMap(
(cp) -> cp < 128 // ASCII?
? IntStream.of(cp)
: String.format("&#x%X;", cp).codePoints())
.toArray();
return new String(codePoints, 0, codePoints.length);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.