java中properties文件路径的访问及XML字符编码问题

来源:互联网 发布:淘宝代销和经销的区别 编辑:程序博客网 时间:2024/05/22 14:49

在Eclipse中新建一个java工程,并新建源代码目录config,在config目录中新建一个名为config的包,在config包中放入两个配置文件,并且都以UTF-8编码存储:

test.properties

测试=测试test=测试 

config.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"><properties><comment>Temporary Properties</comment><entry key="TWO">2</entry><entry key="ONE">1</entry><entry key="한국어">한국어</entry><entry key="Thảo luận tiếng Việt">Thảo luận tiếng Việt</entry><entry key="日本語">日本語はどう?</entry><entry key="中文">看看中文怎么样</entry></properties>

main方法实现如下:

    public static void main( String[] args ) throws Exception    {         Properties props=new Properties();        System.out.println(Object.class.getResource("/").getPath());        System.out.println(Object.class.getResource("/config/test.properties").getFile());        InputStream in =Object.class.getResourceAsStream("/config/test.properties");        props.load(in);        props.setProperty("0010", "OK1");        props.setProperty("0012", "OK2");        String s=props.getProperty(new String("测试".getBytes("UTF-8"),"ISO8859-1"));        s=new String(s.getBytes("ISO8859-1"),"UTF-8");        System.out.println(s);        in =Object.class.getResourceAsStream("/config/config.xml");        props.loadFromXML(in);        System.out.println(props.getProperty("中文"));    }

Object.class.getResource和Object.class.getResourceAsStream方法可以通过"/config/...“这样的类加载路径加包名的形式访问到对应的properties文件。注意properties文件默认使用ISO8859-1编码,所以使用UTF-8编码时使用了转换,而xml格式的配置文件就不存在编码转换的问题。

0 0
原创粉丝点击