【问题标题】:JDK 1.5 Properties load with unicode charactersJDK 1.5 属性使用 unicode 字符加载
【发布时间】:2014-07-08 18:11:20
【问题描述】:

JDK 1.5 属性 load 方法仅获取 InputStream 而 JDK 1.6+ load 方法也获取 Reader。当使用 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=ÇÇÇÇ

【问题讨论】:

  • 一般来说,您需要在属性文件中使用 unicode 转义符,以便使用 InputStream(即 \u00FF 类型的替换)正确加载它们。

标签: java unicode jdk1.5


【解决方案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);

【讨论】:

  • 这会产生编译错误。 charset 不能在 getBytes 中使用。
【解决方案2】:

因此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));
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多