[英]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.