java读取ApplicationResources.properties资源文件

来源:互联网 发布:网络配线架的作用 编辑:程序博客网 时间:2024/05/21 15:06

 java读取ApplicationResources.properties资源文件 (转贴)

java读取ApplicationResources.properties资源文件

有时做系统时会有这样的需要,直接读取

ApplicationResources.properties资源文件

//代码里直接读取资源文件内容可以使用如下测试代码,修改即可用。下面第一句是找到资源文件,这里是直接找classes的目录
  InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("ApplicationResources.properties");
  Properties props = new Properties();
  props.load(inputStream);
  System.out.println(props.getProperty("common.batchEdit.message")); 

//上代码输出:请选择要编辑的记录,common.batchEdit.message 为资源文件里的key。资源文件一般会放转码过后的编码,例如:common.batchEdit.message=/u8bf7/u9009/u62e9/u8981/u7f16/u8f91/u7684/u8bb0/u5f55/uff01,直接使用props.getProperty  可以直接输出转码后的内容。

//如果代码这样写

 Properties props=new Properties();
 props.load(BugFactory.class.getResourceAsStream("ApplicationResources.properties"));
 String name = props.getPropery("common.batchEdit.message");
 此时ApplicationResources.properties应该与该类放在同一个目录.

还有一种方法:

ResourceBundle res = ResourceBundle.getBundle("yy.properties");
 String name = res.getString("yyyy");
 yy.properties应放在/WEB-INF/classes目录

如果你这个Bean打包的话,就把这个文件放在包内。

我一般是这样写的
Properties prop = new Properties();
try
{
 InputStream is = getClass().getResourceAsStream("db.properties");
 prop.load(is);
 if(is!=null)
    is.close();
}
另外一些说明:
props.load(new FileInputStream("db.properties")); 是读取当前目录的db.properties文件
getClass.getResourceAsStream("db.properties"); 是读取当前类所在位置一起的db.properties文件
getClass.getResourceAsStream("/db.properties"); 是读取ClassPath的根的db.properties文件,注意ClassPath如果是多个路径或者jar文件的,只要在任意一个路径目录下或者jar文件里的根下都可以,如果存在于多个路径下的话,按照ClassPath中的先后顺序,使用先找到的,其余忽略.
原创粉丝点击