您的位置:首页 > 编程语言 > Java开发

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

2016-04-24 21:34 447 查看
在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格式的配置文件就不存在编码转换的问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: