如題,想用java把八進制轉義后的 UTF-8 序列轉換成原本的字串,參考這個網頁(https://ask.csdn.net/questions/714755),在本地嘗試了一下,發現8進制轉成中文以后一直有亂碼的問題,即使把 return new String(arr,"UTF-8"); 的UTF-8換成unicode或gbk也有同樣的問題。
說明:本地因為沒有裝開發工具,直接在cmd里運行吧,在cmd里改編碼方式(chcp 65001 )同樣不管用。
import java.io.UnsupportedEncodingException;
public class HelloWorld {
public static String toOct(String s)
{
String result = "";
byte[] bytes = s.getBytes();
for (byte b : bytes)
{
int b1 = b;
if (b1 < 0) b1 = 256 + b1;
result += "\\" + (b1 / 64) % 8 + "" + (b1 / 8) % 8 + "" + b1 % 8;
}
return result;
}
public static String getOct(String s) throws UnsupportedEncodingException
{
String[] as = s.split("\\\\");
byte[] arr = new byte[as.length - 1];
for (int i = 1; i < as.length; i++)
{
int sum = 0;
int base = 64;
for (char c : as[i].toCharArray())
{
sum += base * ((int)c - '0');
base /= 8;
}
if (sum >= 128) sum = sum - 256;
arr[i - 1] = (byte)sum;
}
return new String(arr,"UTF-8"); //如果還有亂碼,這里編碼方式你可以修改下,比如試試看UTF-8 unicode gbk等等
}
public static void main(String[] args) throws java.io.UnsupportedEncodingException {
//String s = "123中文";
//String o = toOct(s);
String o = "\061\062\063\344\270\255\346\226\207";
String s = getOct(o);
System.out.println(o);
//s = getOct(o);
System.out.println(s);
}
}
uj5u.com熱心網友回復:
自己先頂一下轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/157242.html
標籤:Java SE
上一篇:spring tool suite(STS)版本與spring開發包的關系;STS4.5.1配置那個版本的jar包?請幫忙解答一下,不勝感謝
