当前位置:编程学习 > JAVA >>

请教读Properties时,UTF-8的值保持不变?

比如info.properites文件里面包括3 key-values
hello=\u4F60\u597D
hi=How are you?
error=info is not correct!

通过Java如何把UTF-8编码 “hello=\u4F60\u597D” 读出来而不是decode之后的“hello=你好”? UTF-8 Java --------------------编程问答-------------------- 这个编码是unicode, 不是utf-8.下面代码参考一下:


public class GetOriginalUnicode {
public static void main(String[] args) throws Exception
{
//测试1
String hello="\u4F60\u597D";
String newHello = getUnicode(hello);
System.out.println("hello is "+hello);
System.out.println("newHello is "+newHello);
//测试2
hello = "中国";
newHello = getUnicode(hello);
System.out.println("hello is "+hello);
System.out.println("newHello is "+newHello);
}
//把字符串转成 unicode 形式
public static String getUnicode(String s) throws Exception
{
if(null == s || "".equals(s))//字符串空返回null
{
return null;
}
byte[] b = s.getBytes("unicode");//把字符串按unicode 转成byte数组。
StringBuilder sb = new StringBuilder();//建立Stringbuilder 对象

for(int i = 2; i< b.length; i+=2){//数组前两个字节为标志编码,跳过。
sb.append("\\u");
String str = (b[i]>0)?Integer.toHexString(b[i]):Integer.toHexString(b[i]).substring(6);
sb.append(str);
str = (b[i+1]>0)?Integer.toHexString(b[i+1]):Integer.toHexString(b[i+1]).substring(6);
sb.append(str);
}
return sb.toString();
}
}
--------------------编程问答-------------------- 谢谢nmyangym!
我的意思是每当从properties文件读到“hello=\u4F60\u597D”已经编码的键值,就输出同样的值。希望得到这样的: props.getProperty ("hello") => \u4F60\u597D,有什么办法?

--------------------编程问答-------------------- 就用上面的静态方法就行啊.
1 你得到了字符串变量 s = "你好"; 
2 把 s 作为参数,传给方法getUnicode(String s) 即得到你要的结果。
   String hello = getUnicode(s);
3 结果就是你要的格式。
补充:Java ,  Java SE
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,