为什么即使在设置了file.encoding的情况下,在属性文件中使用Unicode也不起作用,但实际字符却不起作用?

问题描述 投票:1回答:1

这里是test.properties文件。

mycharacters=ýþÿƛƸ
myotherchars=\u00FD\u00FE\u00FF\u019B\u01B8

这里是使用的代码:

import java.awt.FlowLayout;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ResourceBundle;

import javax.swing.*;

public class MultiByteTest2 
{
    public MultiByteTest2()
    {
        ResourceBundle bundle = ResourceBundle.getBundle("test");
        JFrame frame = new JFrame("MultiByte Test");

        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());

        JLabel label1 = new JLabel(bundle.getString("mycharacters"));
        JLabel label2 = new JLabel("  ---  " + bundle.getString("myotherchars"));

        panel.add(label1);
        panel.add(label2);

        String defaultCharacterEncoding = System.getProperty("file.encoding");
        System.out.println("defaultCharacterEncoding by property: " + defaultCharacterEncoding);
        System.out.println("defaultCharacterEncoding by code: " + getDefaultCharEncoding());
        System.out.println("defaultCharacterEncoding by charSet: " + Charset.defaultCharset());

        frame.add(panel);
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }
    public static void main(String s[]) 
    {
        MultiByteTest2 myObject = new MultiByteTest2();

    }

    public static String getDefaultCharEncoding(){
        byte [] bArray = {'w'};
        InputStream is = new ByteArrayInputStream(bArray);
        InputStreamReader reader = new InputStreamReader(is);
        String defaultCharacterEncoding = reader.getEncoding();
        return defaultCharacterEncoding;
    }

}

这里是输出:

enter image description here

运行以上代码的命令和显示正在使用UTF-8的输出。

 >java -Dfile.encoding=UTF-8 MultiByteTest2
 Picked up _JAVA_OPTIONS: -Dfile.encoding=UTF-8
 defaultCharacterEncoding by property: UTF-8
 defaultCharacterEncoding by code: UTF8
 defaultCharacterEncoding by charSet: UTF-8

三个问题:

  1. 为什么使用实际字符会导致输出混乱的字符?

  2. 为什么使用Unicode表示法起作用?

  3. 输出显示的是UTF-8而不是cp1252,这表明正在使用file.encoding,但是为什么在属性文件中使用实际字符时却无济于事?

java unicode properties-file
1个回答
1
投票

*。properties使用ISO-8859-1,拉丁文1。这是一个非常古老的设计决定。通过u转义可以读取Unicode。

我认为最干净的解决方案是使用Properties类,也许还使用XML属性(loadFromXML)。 XML也可以保存在应用程序外部,这对于国际化可能是有用的。

[在Maven构建中,也可以将UTF-8中的预构建* .properties转换为u转义的* .properties。这是带有过滤的Maven副本。

© www.soinside.com 2019 - 2024. All rights reserved.