JDK 1.5属性使用unicode字符加载

时间:2014-07-08 08:16:23

标签: java unicode jdk1.5

JDK 1.5属性load方法仅获取InputStream,而JDK 1.6 + load方法也获得Reader。当带有Unicode字符的字符串加载到带有加载(阅读器)的JDK 1.6+上的属性对象时,没有问题。但是在JDK 1.5上只有load(InputStream)方法;当加载到属性时,unicode字符未正确加载。

Properties props = new Properties();
ByteArrayInputStream bis = null;
Reader reader = null;
try {
        bis = new ByteArrayInputStream(someStringWithUnicodeChars.getBytes("UTF-8"));
        reader = new InputStreamReader(bis, "UTF-8");
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }

props.load(reader); // This reads unicode characters correctly on JDK 1.6+

// There is no props.load(reader) method on JDK 1.5, so below method is used
props.load(bis);
// but Unicode characters are not loaded correctly.

如何将以下带有unicode字符的示例字符串加载到属性对象。

key1=test İ Ş Ğ
key2=ÇÇÇÇ

2 个答案:

答案 0 :(得分:1)

来自1.5 javadoc“假设流使用ISO 8859-1字符编码” http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Properties.html#load(java.io.InputStream)

试试这个:

InputStream in = new ByteArrayInputStream(someStringWithUnicodeChars.getBytes("ISO-8859-1"));
Properties props = new Properties();
props.load(in);

答案 1 :(得分:0)

因此,JDK中存在工具native2ascii [.exe]。

1) create the properties file as UTF-8, name it for example: sample.native
2) convert the native properties file to Unicode escape sequences: native2ascii prop.native > prop.properties
3) load and process the properties file

// example: you will see the right UTF-8 characters only if your console suppert UTF-8
class PropsFile {
    public static void main(String[] args) throws Exception {
        try (FileInputStream fis = new FileInputStream("sample.properties")) {
            Properties props = new Properties();
            props.load(fis);
            for (String name : props.stringPropertyNames()) {
                System.out.println(name + "=" + props.getProperty(name));
            }
        }
    }
}