java中properties文件路径的访问及字符编码问题
2016-04-24 21:34
447 查看
在Eclipse中新建一个java工程,并新建源代码目录config,在config目录中新建一个名为config的包,在config包中放入两个配置文件,并且都以UTF-8编码存储:
test.properties
config.xml
main方法实现如下:
Object.class.getResource和Object.class.getResourceAsStream方法可以通过"/config/...“这样的类加载路径加包名的形式访问到对应的properties文件。注意properties文件默认使用ISO8859-1编码,所以使用UTF-8编码时使用了转换,而xml格式的配置文件就不存在编码转换的问题。
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格式的配置文件就不存在编码转换的问题。
相关文章推荐
- java.util包---HashSet
- Java大牛养成记(5)——The content of element type "struts" must match "(package|include|bean|constant)*".
- 【SSH】Spring简介和应用
- 安卓开发之java基础篇笔记【1】
- 重新学javaweb---路径专题
- @Repository、@Service、@Controller 和 @Component
- IT忍者神龟之Java获取各种常用时间
- springmvc中的controller中的几种参数绑定
- SpringMVC+hibernate整合小例子,用户的增删查改
- 20145222黄亚奇《Java程序设计》第8周学习总结
- 20145328 《Java程序设计》第8周学习总结
- 方便好使的java.util.Properties类
- 20145331 《Java程序设计》第8周学习总结
- Spring MVC初体验之xml配置文件
- Spring4.2.6 ----注解大全[未完成]
- java枚举
- Java 泛型
- java.util包---HashMap
- Java 异常处理机制
- java的面向对象