欧元符号未在适当的文件中显示正确

gav*_*ask 1 java character-encoding java-ee properties-file

我正在阅读一个包含欧元符号的属性文件.当它在屏幕上打印时看起来完全不同.我比较了来自props文件的字符串,并使用equals方法声明另一个带有相同文本的字符串,这是假的.Pls可以有人帮助我.

properities file
your purchase order is €

string text="your purchase order is €";

on comparing the above strings it fails.

************************
public String getProperty(String arg0) {
        Properties prop = new Properties();
        InputStream input = null;


            try {
                input = new FileInputStream("C:/text.properties");

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {

                prop.load(input);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        return prop.getProperty(arg0);

    }
Run Code Online (Sandbox Code Playgroud)

Ian*_*rts 5

假定文件以字符编码保存的Properties.load方法,该方法不能直接表示欧元符号.如果文件实际上是使用不同的编码(如UTF-8),那么您应该使用取代的方法,并使用a 来指定正确的编码.InputStreamISO-8859-1loadReaderInputStreamReader

或者,Properties文件支持Unicode转义序列,因此您可以\u20ac在文件中表示欧元符号,并在加载文件时将其解码为真实字符.

除此之外,您当前的代码中存在许多缺陷,最重要的是您需要确保在从中加载属性后正确关闭输入流.最简单的方法是使用"try with resources"语法

try(InputStream in = new FileInputStream("C:/text.properties");
    InputStreamReader reader = new InputStreamReader(in, "UTF-8")) {
  prop.load(reader);
} catch (IOException e) {
  e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

每次从中请求值时重新加载属性文件似乎都很浪费,您可以考虑只加载一次(在前面或第一次请求它)并缓存Properties对象供以后使用.