日期:2014-05-20  浏览次数:20702 次

java中Properites的使用问题
java类中读取资源文件,资源文件是Properites形式的,应该怎么样去读取,返回给我的是一个什么形式的呢?
初学者求教。。

------解决方案--------------------
properties里面应该是这种形式:
author=zeige
team=SUTMOUNTING
campus=\u5927\u8FDE\u6C11\u65CF\u5B66\u9662
使用方法也挺简单的:
InputStream in = this.getClass().getResourceAsStream("test.properties");
  Properties p = new Properties();
  p.load(in);
然后直接p.get(author);这样就行了,
个人感觉properties里面有可能存了一个Map吧,本人比较懒,未看过源码。
------解决方案--------------------
就拿一个普通的jdbc配置文件来说。这个db.properties配置文件一般存放在项目的src目录下
private static String username = null;
private static String password = null;
private static String url = null;

static {
String path = JdbcUtils.class.getClassLoader().getResource("db.properties").getPath();
Properties properties = new Properties();
try {
properties.load(new FileInputStream(path));
String driverClass = properties.getProperty("driver");
username = properties.getProperty("username");
password = properties.getProperty("password");
url = properties.getProperty("url");
} catch (Exception e) {
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}


上面的代码是放到一个jdbc的工具类中的.配置文件在整个项目运行的过程中只需要加载一次。所以放在静态代码块中。加载完后根据key取出里面的数据就行了。
------解决方案--------------------

Properties p = new Properties();
//加载属性文件,注意路径为当前类目录下
p.load(this.getClass().getResourceAsStream("hello.properties"));
p.get("hi");//获取值

------解决方案--------------------
Properties类继承HashTable类,HashTable是一个线程安全的键值对的集合,Properties类会先将文件中的键值对读取出来,放在内存中的键值对集合中,这一就可以像操控普通的map一样进行get(key)的读取操作了