简体   繁体   English

java:方括号的属性文件转义序列

[英]java : properties file escape sequence for square bracket

Need to escape the [ at the starting of a value. 需要在值的开头转义[。

I am using PropertyResourceBundle to read the properties file and i have a property whose value is starting with a square bracket like 我正在使用PropertyResourceBundle读取属性文件,并且我有一个属性的值以方括号开头,例如

myapp.add.user.email.selfRegistration.subject=[MYAPP] Welcome to MYAPP

when i try to read this file i get following exception 当我尝试读取此文件时,出现以下异常

java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to
java.lang.String    at
java.util.ResourceBundle.getString(ResourceBundle.java:355)

i am using jdk7 我正在使用jdk7

java.util.PropertyResourceBundle is based on the java.util.Properties . java.util.PropertyResourceBundle基于java.util.Properties Technically java.util.Properties implements Map<Object,Object> but when you load properties from a file the keys and values are restricted to String only (check the source of the java.util.Properties.load() methods). 从技术上讲, java.util.Properties实现Map<Object,Object>但是当您从文件加载属性时,键和值仅限于String (请检查java.util.Properties.load()方法的源)。 And the '[' character has no special meaning in the properties file format. 在属性文件格式中,“ [”字符没有特殊含义。

Hence it is impossible to get ClassCastException due to attempted cast of String[] to String if all your resource bundles are indeed based on property files. 因此,它是不可能得到ClassCastException因企图施放String[]String ,如果所有的资源包确实是基于属性文件。

Most likely you have a ListResourceBundle -based bundle (or a custom subclass of ResourceBundle ) which can contain values of any type, arrays included. 您最有可能具有基于ListResourceBundle的捆绑包(或ResourceBundle的自定义子类),该捆绑包可以包含任何类型的值,包括数组。

And it is possible to mix property-based and class-based resources bundles with the same base name, for example the default resource bundle can be properties file while locale-specific child bundles are ListResourceBundle -based. 并且可以混合使用具有相同基本名称的基于属性的资源和基于类的资源束,例如,默认资源束可以是属性文件,而特定于语言环境的子束是基于ListResourceBundle的。

I tried the same with the below program and i am able to get the output from my program without any exception 我用下面的程序尝试了同样的方法,我可以毫无例外地从程序中获取输出

can you check it and let me know if any other issues 你可以检查一下,让我知道是否还有其他问题

package com.kb;

import java.util.Enumeration;
import java.util.ResourceBundle;

public class ResourceBundleTest {
    public static void main(String[] args) {

        ResourceBundle rb = ResourceBundle.getBundle("mybundle");
        Enumeration <String> keys = rb.getKeys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            String value = rb.getString(key);
            System.out.println(key + ": " + value);
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM