若是java web项目,项目运行于tomcat或其他容器时,可以使用下面方式来获取文件的输入流

1、当属性文件放在src下面时

InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("test.properties");
Properties p = new Properties();
p.load(is);

2、当属性文件放在某个包下面时,如:com.test.config

InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/test/config/test.properties");
Properties p = new Properties();
p.load(is);

若是java项目,则使用下面方法读取属性文件

InputStream is = ClassLoader.getSystemResourceAsStream("test.properties");
Properties p = new Properties();
p.load(is);
若属性文件放在某个包下面,则使用com/test/config/test.properties即可

*.properties格式的文件在java中用的还是挺多的,可以说写java项目时只要有配置数据基本都会使用*.properties来做,这也是java官方支持的一种配置文件,jdk提供了现成的api来操作。

在eclipse中使用properties格式的文件时,默认会将properties文件中的中文转成asc码,这时我们可以给eclipse安装一个properties编辑器插件就可以支持中文显示了。

properties编辑器插件下载地址:http://download.csdn.net/detail/abc_key/7482089

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐