properties配置文件中文乱码解决方法

方法1   properties文件的格式一般为:

ROOT=http://localhost:8080/BNCAR2/

ROOTPATH=E:/ws2/BNCAR2/rel/

 

MALL_PARTS_PATH=mall.jsp?rowid=0&typeFlag=0&pid=32

MALL_AFFIX_PATH=mall.jsp?rowid=0&typeFlag=1&pid=74



MALL_TYPE_TAG1=保养套装

MALL_TYPE_TAG2=系统养护

MALL_TYPE_TAG3=轮胎轮毂



NETWORK_TAG1=上海

NETWORK_TAG2=江苏

以上为保存UTF-8格式,使用UltraEdit编辑,避免出现空格导致转码错误。(在文本编辑器中有时候空格看不出来,这就是看似中文对了,实际转码会存在非法字符的原因了~!!)
java中获取配件文件信息,PropUtil.java

static Properties config = null;

    static String filename = PropUtil.class.getClassLoader().getResource("bn-context.properties").getFile();

    static Logger log = Logger.getLogger(PropUtil.class);

    

    public PropUtil() {

        super();

        config = getPropUtil();

    }



    public static Properties getPropUtil() {

        config = new Properties();

        InputStream is = null;

        try {

             //ln("初始化config对象!");

            is = PropUtil.class.getClassLoader().getResourceAsStream(

                    "bn-context-test.properties");

            config.load(is);

        } catch (IOException e) {

            e.printStackTrace();

        } finally {// 关闭资源

            if (is != null) {

                try {

                    is.close();

                } catch (IOException e) {

                }

            }

        }

        return config;

    }



    public static String getParameter(String key) {

        if(config == null){

            config = getPropUtil();

        }

        String value = config.getProperty(key);

        // 编码转换,从ISO8859-1转向指定编码



        try {

            if(value != null){

                value = new String(value.getBytes("ISO8859-1"), "UTF-8");

            }

        } catch (UnsupportedEncodingException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        

        return value;

    }

    

    public static void setParameter(String key,String value) {

        if(config == null){

            config = getPropUtil();

        }

        config.setProperty(key, value);

    }

 

方法2  用UltraEdit编辑器,编写中文配置文件bn-context-test.properties,在保存后再点击另存为,文件名为prop.properties,编码选择unicode ascii就可以了。

ROOT=http://localhost:8080/BNCAR2/

ROOTPATH=E:/ws2/BNCAR2/rel/

 

MALL_PARTS_PATH=mall.jsp?rowid=0&typeFlag=0&pid=32

MALL_AFFIX_PATH=mall.jsp?rowid=0&typeFlag=1&pid=74



MALL_TYPE_TAG1=\u4FDD\u517B\u5957\u88C5

MALL_TYPE_TAG2=\u7CFB\u7EDF\u517B\u62A4

MALL_TYPE_TAG3=\u8F6E\u80CE\u8F6E\u6BC2



NETWORK_TAG1=\u4E0A\u6D77

NETWORK_TAG2=\u6C5F\u82CF

如果这种情况,以上java代码就不需要转码那部分代码,注释掉。

        // 编码转换,从ISO8859-1转向指定编码



//        try {

//            if(value != null){

//                value = new String(value.getBytes("ISO8859-1"), "UTF-8");

//            }

//        } catch (UnsupportedEncodingException e) {

//            // TODO Auto-generated catch block

//            e.printStackTrace();

//        }

 

 

你可能感兴趣的:(properties)