[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[整理]java操作properties文件小总结

上一篇:[随笔]暮色中,一只小麻雀孤独的在5楼的窗台上张望
下一篇:[备忘]RCP开发中,Java代码是UTF-8编码,导出时报错的解决办法

添加日期:2011/3/11 14:30:34 快速返回   返回列表 阅读3940次
转:

1. 资源文件所存放的位置
   资源文件放在classpath下,即工程项目的class包下

2. 获取系统资源文件的方式有2中
   a.  通过  InputStream inputstream = ClassLoader.getSystemResourceAsStream("info.properties"); 
   b. 通过 InputStream inputstream = this.getClass().getResourceAsStream("/info.properties");

采用第一种方式获取资源文件时,文件不以"/" 开头,而采用方法b的话,文件必须"/"开头

3. 提取加载资源文件的信息


Properties properties = new Properties();
InputStream inputstream = ClassLoader.getSystemResourceAsStream("info.properties");
// InputStream inputstream = this.getClass().getResourceAsStream("/info.properties");
 
properties.load(inputstream);


 

4. 操作资源文件
   a. 根据key值在资源文件中查询value值
      1. getProperty(String key) 用指定的键在此属性列表中搜索属性。
      2. getProperty(String key, String defaultValue)   用指定的键在属性列表中搜索属性。
     
   b. 获取所有的键值对的信息

 Enumeration<String> enumvalue = (Enumeration<String>) properties.propertyNames();// 返回属性列表中所有键的枚举,如果在主属性列表中未找到同名的键,则包括默认属性列表中不同的键
 
 while (enumvalue.hasMoreElements())
 {
      String key = enumvalue.nextElement();
      System.out.println(key + " : " + properties.getProperty(key));
 }


 
 
   c. 向资源文件中添加键值信息,如果key值相同就会将原有的信息覆盖


URL url = ClassLoader.getSystemResource("info.properties");
File file = new File(url.toURI());
       
InputStream is = new FileInputStream(file);
properties.load(is);
properties.setProperty("key", "value");
 
OutputStream fos = new FileOutputStream(file);
properties.store(fos, null);
 
fos.flush();
is.close();




  d. 删除相关的键值对

File file = new File(ClassLoader.getSystemResource("info.properties").toURI());
InputStream is = new FileInputStream(file);
 
properties.load(is);
properties.remove("key");
 
OutputStream fos = new FileOutputStream(file);
properties.store(fos, null);
 
is.close();
fos.flush();
fos.close(); 


===============================
Properties这个类是以ISO8859-1编码来读写properties文件的。
store方法,会自动把中文之类的字符转成\uxxxx的形式,所以还可以了。
只是你直接打开properties文件编辑的话,会略有不爽。
eclipse中可以装个插件。
==============================
 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved