如何通过 ResourceBundle 在资源属性中使用 UTF-8

发布于 2024-10-11 07:46:54 字数 147 浏览 11 评论 0 原文

我需要使用 Java 的 ResourceBundle 在资源属性中使用 UTF-8。当我将文本直接输入属性文件时,它显示为 mojibake。

我的应用程序在 Google App Engine 上运行。

谁能给我举个例子吗?我无法完成这项工作。

I need to use UTF-8 in my resource properties using Java's ResourceBundle. When I enter the text directly into the properties file, it displays as mojibake.

My app runs on Google App Engine.

Can anyone give me an example? I can't get this work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

柏拉图鍀咏恒 2024-10-18 07:46:54

Java 9 及更新版本

从 Java 9 开始属性文件默认编码为 UTF-8,使用 ISO-8859-1 之外的字符应该可以开箱即用。

如果您使用 IDE 来编辑它们,那么您可能需要重新指示 IDE 使用 UTF-8 读取它们。以下是在 IntelliJ 设置中执行此操作的方法:

在此处输入图像描述

在 Eclipse 的首选项中:

在此处输入图像描述

Java 8 及更早

版本 ResourceBundle#getBundle() 在幕后使用 PropertyResourceBundle.properties文件被指定。默认情况下,这又使用 Properties#load(InputStream) 加载这些属性文件。根据 javadoc ,它们默认读取为 ISO-8859-1。

public void load(InputStream inStream) 抛出 IOException

从输入字节流中读取属性列表(键和元素对)。输入流采用 load(Reader) 中指定的简单的面向行的格式,并假定使用 ISO 8859-1 字符编码;即每个字节都是一个 Latin1 字符。非 Latin1 字符和某些特殊字符使用 Java™ 语言规范第 3.3 节中定义的 Unicode 转义符在键和元素中表示。

因此,您需要将它们另存为 ISO-8859-1。如果您有任何超出 ISO-8859-1 范围的字符,并且无法在头顶使用 \uXXXX ,因此您被迫将文件保存为 UTF-8,那么您将需要使用 native2ascii< /a> 工具,用于将 UTF-8 保存的属性文件转换为 ISO-8859-1 保存的属性文件,其中所有未覆盖的字符都将转换为 \uXXXX 格式。以下示例将 UTF-8 编码的属性文件 text_utf8.properties 转换为有效的 ISO-8859-1 编码的属性文件 text.properties

native2ascii -encoding UTF-8 text_utf8.properties text.properties

使用 Eclipse 或 IntelliJ 等 IDE 时,当您在基于 Java 的项目中创建 .properties 文件并使用 IDE 自己的属性文件编辑器时,这已经自动完成。它将透明地将超出 ISO-8859-1 范围的字符转换为 \uXXXX 格式。另请参阅下面的 Eclipse 屏幕截图(请注意底部的“属性”和“源”选项卡,单击查看大图):

“属性”选项卡

或者,您也可以创建自定义 < a href="http://docs.oracle.com/javase/7/docs/api/java/util/ResourceBundle.Control.html" rel="noreferrer">ResourceBundle.Control 实现,其中您使用 InputStreamReader,这样您就可以将它们保存为 UTF-8,而无需麻烦 native2ascii。这是一个启动示例:

public class UTF8Control extends Control {
    public ResourceBundle newBundle
        (String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
            throws IllegalAccessException, InstantiationException, IOException
    {
        // The below is a copy of the default implementation.
        String bundleName = toBundleName(baseName, locale);
        String resourceName = toResourceName(bundleName, "properties");
        ResourceBundle bundle = null;
        InputStream stream = null;
        if (reload) {
            URL url = loader.getResource(resourceName);
            if (url != null) {
                URLConnection connection = url.openConnection();
                if (connection != null) {
                    connection.setUseCaches(false);
                    stream = connection.getInputStream();
                }
            }
        } else {
            stream = loader.getResourceAsStream(resourceName);
        }
        if (stream != null) {
            try {
                // Only this line is changed to make it to read properties files as UTF-8.
                bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8"));
            } finally {
                stream.close();
            }
        }
        return bundle;
    }
}

可以按如下方式使用:

ResourceBundle bundle = ResourceBundle.getBundle("com.example.i18n.text", new UTF8Control());

另请参阅:

Java 9 and newer

From Java 9 onwards property files are encoded as UTF-8 by default, and using characters outside of ISO-8859-1 should work out of the box.

In case you're using an IDE to edit them, then you may need to reinstruct the IDE to read them using UTF-8. Here's how to do that in IntelliJ's settings:

enter image description here

And in Eclipse's preferences:

enter image description here

Java 8 and older

The ResourceBundle#getBundle() uses under the covers PropertyResourceBundle when a .properties file is specified. This in turn uses by default Properties#load(InputStream) to load those properties files. As per the javadoc, they are by default read as ISO-8859-1.

public void load(InputStream inStream) throws IOException

Reads a property list (key and element pairs) from the input byte stream. The input stream is in a simple line-oriented format as specified in load(Reader) and is assumed to use the ISO 8859-1 character encoding; that is each byte is one Latin1 character. Characters not in Latin1, and certain special characters, are represented in keys and elements using Unicode escapes as defined in section 3.3 of The Java™ Language Specification.

So, you'd need to save them as ISO-8859-1. If you have any characters beyond ISO-8859-1 range and you can't use \uXXXX off top of head and you're thus forced to save the file as UTF-8, then you'd need to use the native2ascii tool to convert an UTF-8 saved properties file to an ISO-8859-1 saved properties file wherein all uncovered characters are converted into \uXXXX format. The below example converts a UTF-8 encoded properties file text_utf8.properties to a valid ISO-8859-1 encoded properties file text.properties.

native2ascii -encoding UTF-8 text_utf8.properties text.properties

When using an IDE such as Eclipse or IntelliJ, this is already automatically done when you create a .properties file in a Java based project and use IDE's own properties file editor. It will transparently convert the characters beyond ISO-8859-1 range to \uXXXX format. See also below screenshots from Eclipse (note the "Properties" and "Source" tabs on bottom, click for large):

"Properties" tab "Source" tab

Alternatively, you could also create a custom ResourceBundle.Control implementation wherein you explicitly read the properties files as UTF-8 using InputStreamReader, so that you can just save them as UTF-8 without the need to hassle with native2ascii. Here's a kickoff example:

public class UTF8Control extends Control {
    public ResourceBundle newBundle
        (String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
            throws IllegalAccessException, InstantiationException, IOException
    {
        // The below is a copy of the default implementation.
        String bundleName = toBundleName(baseName, locale);
        String resourceName = toResourceName(bundleName, "properties");
        ResourceBundle bundle = null;
        InputStream stream = null;
        if (reload) {
            URL url = loader.getResource(resourceName);
            if (url != null) {
                URLConnection connection = url.openConnection();
                if (connection != null) {
                    connection.setUseCaches(false);
                    stream = connection.getInputStream();
                }
            }
        } else {
            stream = loader.getResourceAsStream(resourceName);
        }
        if (stream != null) {
            try {
                // Only this line is changed to make it to read properties files as UTF-8.
                bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8"));
            } finally {
                stream.close();
            }
        }
        return bundle;
    }
}

This can be used as follows:

ResourceBundle bundle = ResourceBundle.getBundle("com.example.i18n.text", new UTF8Control());

See also:

话少情深 2024-10-18 07:46:54

假设您有一个 ResourceBundle 实例,并且您可以通过以下方式获取 String:

String val = bundle.getString(key); 

我通过以下方式解决了日语显示问题:

return new String(val.getBytes("ISO-8859-1"), "UTF-8");

Given that you have an instance of ResourceBundle and you can get String by:

String val = bundle.getString(key); 

I solved my Japanese display problem by:

return new String(val.getBytes("ISO-8859-1"), "UTF-8");
计㈡愣 2024-10-18 07:46:54

看看这个: http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#load(java.io.Reader)

属性接受 Reader对象作为参数,您可以从 InputStream 创建该对象。

在创建时,您可以指定 Reader 的编码:

InputStreamReader isr = new InputStreamReader(stream, "UTF-8");

然后将此 Reader 应用于加载方法:

prop.load(isr);

BTW:从 .properties 文件获取流:

 InputStream stream = this.class.getClassLoader().getResourceAsStream("a.properties");

BTW:获取资源包InputStreamReader的strong>:

ResourceBundle rb = new PropertyResourceBundle(isr);

希望这可以帮助您!

look at this : http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#load(java.io.Reader)

the properties accept an Reader object as arguments, which you can create from an InputStream.

at the create time, you can specify the encoding of the Reader:

InputStreamReader isr = new InputStreamReader(stream, "UTF-8");

then apply this Reader to the load method :

prop.load(isr);

BTW: get the stream from .properties file :

 InputStream stream = this.class.getClassLoader().getResourceAsStream("a.properties");

BTW: get resource bundle from InputStreamReader:

ResourceBundle rb = new PropertyResourceBundle(isr);

hope this can help you !

无妨# 2024-10-18 07:46:54

这个问题终于在 Java 9 中得到了修复:
https://docs.oracle.com/javase/9​​/intl/internationalization-enhancements-jdk-9

属性文件的默认编码现在为 UTF-8。

大多数现有属性文件不应受到影响:UTF-8 和
ISO-8859-1 对 ASCII 字符具有相同的编码,并且
人类可读的非 ASCII ISO-8859-1 编码不是有效的 UTF-8。如果一个
检测到无效的 UTF-8 字节序列,Java 运行时
自动重新读取 ISO-8859-1 中的文件。

This problem has finally been fixed in Java 9:
https://docs.oracle.com/javase/9/intl/internationalization-enhancements-jdk-9

Default encoding for properties files is now UTF-8.

Most existing properties files should not be affected: UTF-8 and
ISO-8859-1 have the same encoding for ASCII characters, and
human-readable non-ASCII ISO-8859-1 encoding is not valid UTF-8. If an
invalid UTF-8 byte sequence is detected, the Java runtime
automatically rereads the file in ISO-8859-1.

那支青花 2024-10-18 07:46:54

例如,如果属性文件使用 cp1251 字符集,则使用 UTF-8 和新 String 方法的 ResourceBundle.Control 不起作用。

所以我推荐使用一个通用的方法:用unicode符号编写。为此:

IDEA -- 有一个特殊的"透明本机到 ASCII 转换选项(设置 > 文件编码)。

Eclipse -- 有一个插件"属性编辑器"< /em>。它可以作为单独的应用程序运行。

ResourceBundle.Control with UTF-8 and new String methods don't work, if the properties file uses cp1251 charset, for example.

So I recomended using a common method: write in unicode symbols. For this:

IDEA -- has a special "Transparent native-to-ASCII conversion" option (Settings > File Encoding).

Eclipse -- has a plugin "Properties Editor". It can work as separate application.

暮光沉寂 2024-10-18 07:46:54
package com.varaneckas.utils;  

import java.io.UnsupportedEncodingException;  
import java.util.Enumeration;  
import java.util.PropertyResourceBundle;  
import java.util.ResourceBundle;  

/** 
 * UTF-8 friendly ResourceBundle support 
 *  
 * Utility that allows having multi-byte characters inside java .property files. 
 * It removes the need for Sun's native2ascii application, you can simply have 
 * UTF-8 encoded editable .property files. 
 *  
 * Use:  
 * ResourceBundle bundle = Utf8ResourceBundle.getBundle("bundle_name"); 
 *  
 * @author Tomas Varaneckas <[email protected]> 
 */  
public abstract class Utf8ResourceBundle {  

    /** 
     * Gets the unicode friendly resource bundle 
     *  
     * @param baseName 
     * @see ResourceBundle#getBundle(String) 
     * @return Unicode friendly resource bundle 
     */  
    public static final ResourceBundle getBundle(final String baseName) {  
        return createUtf8PropertyResourceBundle(  
                ResourceBundle.getBundle(baseName));  
    }  

    /** 
     * Creates unicode friendly {@link PropertyResourceBundle} if possible. 
     *  
     * @param bundle  
     * @return Unicode friendly property resource bundle 
     */  
    private static ResourceBundle createUtf8PropertyResourceBundle(  
            final ResourceBundle bundle) {  
        if (!(bundle instanceof PropertyResourceBundle)) {  
            return bundle;  
        }  
        return new Utf8PropertyResourceBundle((PropertyResourceBundle) bundle);  
    }  

    /** 
     * Resource Bundle that does the hard work 
     */  
    private static class Utf8PropertyResourceBundle extends ResourceBundle {  

        /** 
         * Bundle with unicode data 
         */  
        private final PropertyResourceBundle bundle;  

        /** 
         * Initializing constructor 
         *  
         * @param bundle 
         */  
        private Utf8PropertyResourceBundle(final PropertyResourceBundle bundle) {  
            this.bundle = bundle;  
        }  

        @Override  
        @SuppressWarnings("unchecked")  
        public Enumeration getKeys() {  
            return bundle.getKeys();  
        }  

        @Override  
        protected Object handleGetObject(final String key) {  
            final String value = bundle.getString(key);  
            if (value == null)  
                return null;  
            try {  
                return new String(value.getBytes("ISO-8859-1"), "UTF-8");  
            } catch (final UnsupportedEncodingException e) {  
                throw new RuntimeException("Encoding not supported", e);  
            }  
        }  
    }  
}  
package com.varaneckas.utils;  

import java.io.UnsupportedEncodingException;  
import java.util.Enumeration;  
import java.util.PropertyResourceBundle;  
import java.util.ResourceBundle;  

/** 
 * UTF-8 friendly ResourceBundle support 
 *  
 * Utility that allows having multi-byte characters inside java .property files. 
 * It removes the need for Sun's native2ascii application, you can simply have 
 * UTF-8 encoded editable .property files. 
 *  
 * Use:  
 * ResourceBundle bundle = Utf8ResourceBundle.getBundle("bundle_name"); 
 *  
 * @author Tomas Varaneckas <[email protected]> 
 */  
public abstract class Utf8ResourceBundle {  

    /** 
     * Gets the unicode friendly resource bundle 
     *  
     * @param baseName 
     * @see ResourceBundle#getBundle(String) 
     * @return Unicode friendly resource bundle 
     */  
    public static final ResourceBundle getBundle(final String baseName) {  
        return createUtf8PropertyResourceBundle(  
                ResourceBundle.getBundle(baseName));  
    }  

    /** 
     * Creates unicode friendly {@link PropertyResourceBundle} if possible. 
     *  
     * @param bundle  
     * @return Unicode friendly property resource bundle 
     */  
    private static ResourceBundle createUtf8PropertyResourceBundle(  
            final ResourceBundle bundle) {  
        if (!(bundle instanceof PropertyResourceBundle)) {  
            return bundle;  
        }  
        return new Utf8PropertyResourceBundle((PropertyResourceBundle) bundle);  
    }  

    /** 
     * Resource Bundle that does the hard work 
     */  
    private static class Utf8PropertyResourceBundle extends ResourceBundle {  

        /** 
         * Bundle with unicode data 
         */  
        private final PropertyResourceBundle bundle;  

        /** 
         * Initializing constructor 
         *  
         * @param bundle 
         */  
        private Utf8PropertyResourceBundle(final PropertyResourceBundle bundle) {  
            this.bundle = bundle;  
        }  

        @Override  
        @SuppressWarnings("unchecked")  
        public Enumeration getKeys() {  
            return bundle.getKeys();  
        }  

        @Override  
        protected Object handleGetObject(final String key) {  
            final String value = bundle.getString(key);  
            if (value == null)  
                return null;  
            try {  
                return new String(value.getBytes("ISO-8859-1"), "UTF-8");  
            } catch (final UnsupportedEncodingException e) {  
                throw new RuntimeException("Encoding not supported", e);  
            }  
        }  
    }  
}  
眼泪都笑了 2024-10-18 07:46:54

我们创建一个 resources.utf8 文件,其中包含 UTF-8 格式的资源,并有一条运行以下命令的规则:

native2ascii -encoding utf8 resources.utf8 resources.properties

We create a resources.utf8 file that contains the resources in UTF-8 and have a rule to run the following:

native2ascii -encoding utf8 resources.utf8 resources.properties
做个少女永远怀春 2024-10-18 07:46:54

注意:在 Java <= 8 中,java 属性文件应采用 ISO 8859-1 编码!

ISO 8859-1 字符编码。
不能直接使用的字符
在此编码中表示可以是
使用 Unicode 转义符编写;仅有的
允许使用单个“u”字符
转义序列。

@see Properties Java Doc

如果您确实想这样做:请看一下:
Eclipse 中的 Java 属性 UTF-8 编码 -- 有一些代码示例


自 Java 9: 属性文件以 UTF-8 编码,因此应该没有问题/疑问

在 Java SE 9 中,属性文件以 UTF-8 编码加载。在以前的版本中,ISO-8859-1 编码用于加载属性资源包。

(https://docs.oracle.com/javase/9​​/intl/internationalization-enhancements-jdk-9.htm#JSINT-GUID-9DCDB41C-A989-4220-8140-DBFB844A0FCA

Attention: In Java <= 8 java property files should be encoded in ISO 8859-1!

ISO 8859-1 character encoding.
Characters that cannot be directly
represented in this encoding can be
written using Unicode escapes ; only
a single 'u' character is allowed in
an escape sequence.

@see Properties Java Doc

If you still really want to do this: have a look at:
Java properties UTF-8 encoding in Eclipse -- there are some code samples


Since Java 9: property files are encoded in UTF-8, so there should be no problem/doubt

In Java SE 9, properties files are loaded in UTF-8 encoding. In previous releases, ISO-8859-1 encoding was used for loading property resource bundles.

(https://docs.oracle.com/javase/9/intl/internationalization-enhancements-jdk-9.htm#JSINT-GUID-9DCDB41C-A989-4220-8140-DBFB844A0FCA)

凉宸 2024-10-18 07:46:54

http://sourceforge.net/projects/eclipse-rbe/

如前所述,属性文件应该以 ISO 8859-1 进行编码

您可以使用上述 eclipse IDE 插件来为您进行 Unicode 转换。

http://sourceforge.net/projects/eclipse-rbe/

as already stated property files should be encoded in ISO 8859-1

You can use the above plugin for eclipse IDE to make the Unicode conversion for you.

傻比既视感 2024-10-18 07:46:54

这是一个 Java 7 解决方案,它使用 Guava 优秀的支持库和 try-with-resources 构造。它使用 UTF-8 读取和写入属性文件,以获得最简单的整体体验。

读取 UTF-8 格式的属性文件:

File file =  new File("/path/to/example.properties");

// Create an empty set of properties
Properties properties = new Properties();

if (file.exists()) {

  // Use a UTF-8 reader from Guava
  try (Reader reader = Files.newReader(file, Charsets.UTF_8)) {
    properties.load(reader);
  } catch (IOException e) {
    // Do something
  }
}

写入 UTF-8 格式的属性文件:

File file =  new File("/path/to/example.properties");

// Use a UTF-8 writer from Guava
try (Writer writer = Files.newWriter(file, Charsets.UTF_8)) {
  properties.store(writer, "Your title here");
  writer.flush();
} catch (IOException e) {
  // Do something
}

Here's a Java 7 solution that uses Guava's excellent support library and the try-with-resources construct. It reads and writes properties files using UTF-8 for the simplest overall experience.

To read a properties file as UTF-8:

File file =  new File("/path/to/example.properties");

// Create an empty set of properties
Properties properties = new Properties();

if (file.exists()) {

  // Use a UTF-8 reader from Guava
  try (Reader reader = Files.newReader(file, Charsets.UTF_8)) {
    properties.load(reader);
  } catch (IOException e) {
    // Do something
  }
}

To write a properties file as UTF-8:

File file =  new File("/path/to/example.properties");

// Use a UTF-8 writer from Guava
try (Writer writer = Files.newWriter(file, Charsets.UTF_8)) {
  properties.store(writer, "Your title here");
  writer.flush();
} catch (IOException e) {
  // Do something
}
不顾 2024-10-18 07:46:54

正如有人建议的那样,我经历了资源包的实现..但这没有帮助..因为该包总是在 en_US 语言环境下调用...我尝试将我的默认语言环境设置为另一种语言,但仍然是我对资源包的实现正在使用 en_US 调用控件...我尝试放置日志消息并执行调试步骤,看看在运行时通过 xhtml 和 JSF 调用更改区域设置后是否进行了不同的本地调用...这没有发生...然后我尝试将系统设置默认为 utf8 以通过我的服务器(tomcat 服务器)读取文件。但这导致了问题,因为我的所有类库都不是在 utf8 下编译的,而 tomcat 开始以 utf8 格式读取文件服务器没有正常运行...然后我最终在我的java控制器中实现了一个从xhtml文件调用的方法..在该方法中我做了以下操作:

        public String message(String key, boolean toUTF8) throws Throwable{
            String result = "";
            try{
                FacesContext context = FacesContext.getCurrentInstance();
                String message = context.getApplication().getResourceBundle(context, "messages").getString(key);

                result = message==null ? "" : toUTF8 ? new String(message.getBytes("iso8859-1"), "utf-8") : message;
            }catch(Throwable t){}
            return result;
        }

我特别紧张,因为这可能会降低我的应用程序的性能...但是,在实现此操作之后,看起来我的应用程序现在速度更快了..我认为这是因为,我现在直接访问属性而不是让 JSF 解析其访问属性的方式...我特别通过此调用中的布尔参数,因为我知道某些属性不会被翻译,并且不需要采用 utf8 格式...

现在我已将属性文件保存为 UTF8 格式,并且它工作正常,因为我的应用程序中的每个用户都有参考区域设置首选项。

As one suggested, i went through implementation of resource bundle.. but that did not help.. as the bundle was always called under en_US locale... i tried to set my default locale to a different language and still my implementation of resource bundle control was being called with en_US... i tried to put log messages and do a step through debug and see if a different local call was being made after i change locale at run time through xhtml and JSF calls... that did not happend... then i tried to do a system set default to a utf8 for reading files by my server (tomcat server).. but that caused pronlem as all my class libraries were not compiled under utf8 and tomcat started to read then in utf8 format and server was not running properly... then i ended up with implementing a method in my java controller to be called from xhtml files.. in that method i did the following:

        public String message(String key, boolean toUTF8) throws Throwable{
            String result = "";
            try{
                FacesContext context = FacesContext.getCurrentInstance();
                String message = context.getApplication().getResourceBundle(context, "messages").getString(key);

                result = message==null ? "" : toUTF8 ? new String(message.getBytes("iso8859-1"), "utf-8") : message;
            }catch(Throwable t){}
            return result;
        }

I was particularly nervous as this could slow down performance of my application... however, after implementing this, it looks like as if my application is faster now.. i think it is because, i am now directly accessing the properties instead of letting JSF parse its way into accessing properties... i specifically pass Boolean argument in this call because i know some of the properties would not be translated and do not need to be in utf8 format...

Now I have saved my properties file in UTF8 format and it is working fine as each user in my application has a referent locale preference.

往昔成烟 2024-10-18 07:46:54

值得一提的是,我的问题是文件本身的编码错误。使用 iconv 对我有用

iconv -f ISO-8859-15 -t UTF-8  messages_nl.properties > messages_nl.properties.new

For what it's worth my issue was that the files themselves were in the wrong encoding. Using iconv worked for me

iconv -f ISO-8859-15 -t UTF-8  messages_nl.properties > messages_nl.properties.new
我三岁 2024-10-18 07:46:54

我尝试使用 Rod 提供的方法,但考虑到 BalusC 担心不在所有应用程序中重复相同的解决方法,并附带了此类:

import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.ResourceBundle;

public class MyResourceBundle {

    // feature variables
    private ResourceBundle bundle;
    private String fileEncoding;

    public MyResourceBundle(Locale locale, String fileEncoding){
        this.bundle = ResourceBundle.getBundle("com.app.Bundle", locale);
        this.fileEncoding = fileEncoding;
    }

    public MyResourceBundle(Locale locale){
        this(locale, "UTF-8");
    }

    public String getString(String key){
        String value = bundle.getString(key); 
        try {
            return new String(value.getBytes("ISO-8859-1"), fileEncoding);
        } catch (UnsupportedEncodingException e) {
            return value;
        }
    }
}

使用此方法的方法与常规 ResourceBundle 用法非常相似:

private MyResourceBundle labels = new MyResourceBundle("es", "UTF-8");
String label = labels.getString(key)

或者您可以使用默认使用 UTF-8 的替代构造函数:

private MyResourceBundle labels = new MyResourceBundle("es");

I tried to use the approach provided by Rod, but taking into consideration BalusC concern about not repeating the same work-around in all the application and came with this class:

import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.ResourceBundle;

public class MyResourceBundle {

    // feature variables
    private ResourceBundle bundle;
    private String fileEncoding;

    public MyResourceBundle(Locale locale, String fileEncoding){
        this.bundle = ResourceBundle.getBundle("com.app.Bundle", locale);
        this.fileEncoding = fileEncoding;
    }

    public MyResourceBundle(Locale locale){
        this(locale, "UTF-8");
    }

    public String getString(String key){
        String value = bundle.getString(key); 
        try {
            return new String(value.getBytes("ISO-8859-1"), fileEncoding);
        } catch (UnsupportedEncodingException e) {
            return value;
        }
    }
}

The way to use this would be very similar than the regular ResourceBundle usage:

private MyResourceBundle labels = new MyResourceBundle("es", "UTF-8");
String label = labels.getString(key)

Or you can use the alternate constructor which uses UTF-8 by default:

private MyResourceBundle labels = new MyResourceBundle("es");
云之铃。 2024-10-18 07:46:54
Properties prop = new Properties();
String fileName = "./src/test/resources/predefined.properties";
FileInputStream inputStream = new FileInputStream(fileName);
InputStreamReader reader = new InputStreamReader(inputStream,"UTF-8");
Properties prop = new Properties();
String fileName = "./src/test/resources/predefined.properties";
FileInputStream inputStream = new FileInputStream(fileName);
InputStreamReader reader = new InputStreamReader(inputStream,"UTF-8");
夏见 2024-10-18 07:46:54

打开“设置/首选项”对话框 (Ctrl + Alt + S),然后单击“编辑器”和“文件编码”。

所示窗口的屏幕截图

然后,在底部,您将找到属性文件的默认编码。选择您的编码类型。

或者,您可以在资源包中使用 unicode 符号而不是文本(例如 "ів" 等于 \u0456\u0432

Open the Settings / Preferences dialog (Ctrl + Alt + S), then click Editor and File Encodings.

Screenshot of window shown

Then, on the bottom, you will fing default encodings for properties files. Choose your encoding type.

Alternatively you can use unicode symbols instead of text in your resource bundle (for example "ів" equals \u0456\u0432)

狂之美人 2024-10-18 07:46:54

就当前(2021-2)Java 版本而言,仍然存在旧的 ISO-8859-1 函数 utils.Properties#load

请允许我引用官方文档。

属性资源包

PropertyResourceBundle 可以从InputStream 或Reader(表示属性文件)构造。从 InputStream 构造 PropertyResourceBundle 实例需要输入流以 UTF-8 编码。默认情况下,如果在读取输入流时发生 MalformedInputException 或 UnmappableCharacterException,则 PropertyResourceBundle 实例将重置为异常之前的状态,重新读取 ISO-8859-1 中的输入流,并继续读取。 如果系统属性 java.util.PropertyResourceBundle.encoding 设置为“ISO-8859-1”或“UTF-8”,则仅以该编码读取输入流,如果遇到无效序列。如果指定了“ISO-8859-1”,则无法以 ISO-8859-1 编码表示的字符必须由 Unicode 转义符表示(如 Java™ 语言规范第 3.3 节中定义),而采用 Reader 的其他构造函数则不这样做。有这个限制。此系统属性将忽略其他编码值。初始化此类时会读取并评估系统属性。更改或删除该属性在初始化后不会产生任何影响。

https:// docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/PropertyResourceBundle.html

Properties#load

从输入字节流中读取属性列表(键和元素对)。输入流采用 load(Reader) 中指定的简单的面向行的格式,并假定使用 ISO 8859-1 字符编码;即每个字节都是一个 Latin1 字符。非 Latin1 字符和某些特殊字符使用 Java™ 语言规范第 3.3 节中定义的 Unicode 转义符在键和元素中表示。

https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Properties.html#load(java.io.InputStream)

Speaking for current (2021-2) Java versions there is still the old ISO-8859-1 function utils.Properties#load.

Allow me to quote from the official doc.

PropertyResourceBundle

PropertyResourceBundle can be constructed either from an InputStream or a Reader, which represents a property file. Constructing a PropertyResourceBundle instance from an InputStream requires that the input stream be encoded in UTF-8. By default, if a MalformedInputException or an UnmappableCharacterException occurs on reading the input stream, then the PropertyResourceBundle instance resets to the state before the exception, re-reads the input stream in ISO-8859-1, and continues reading. If the system property java.util.PropertyResourceBundle.encoding is set to either "ISO-8859-1" or "UTF-8", the input stream is solely read in that encoding, and throws the exception if it encounters an invalid sequence. If "ISO-8859-1" is specified, characters that cannot be represented in ISO-8859-1 encoding must be represented by Unicode Escapes as defined in section 3.3 of The Java™ Language Specification whereas the other constructor which takes a Reader does not have that limitation. Other encoding values are ignored for this system property. The system property is read and evaluated when initializing this class. Changing or removing the property has no effect after the initialization.

https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/PropertyResourceBundle.html

Properties#load

Reads a property list (key and element pairs) from the input byte stream. The input stream is in a simple line-oriented format as specified in load(Reader) and is assumed to use the ISO 8859-1 character encoding; that is each byte is one Latin1 character. Characters not in Latin1, and certain special characters, are represented in keys and elements using Unicode escapes as defined in section 3.3 of The Java™ Language Specification.

https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Properties.html#load(java.io.InputStream)

鲜血染红嫁衣 2024-10-18 07:46:54

从 Java 9 开始,加载属性文件的默认值已更改为 UTF-8。 https://docs.oracle.com/javase/ 9/intl/国际化-增强-jdk-9.htm

From Java 9, the default to load properties file has been changed to UTF-8. https://docs.oracle.com/javase/9/intl/internationalization-enhancements-jdk-9.htm

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文