`

读取Properties文件和操作的方法

阅读更多
1。使用java.util.Properties类的load()方法 
示例: 
InputStream in = new BufferedInputStream(new FileInputStream(name)); Properties p = new Properties(); 
p.load(in);
 
2。使用java.util.ResourceBundle类的getBundle()方法 
示例:
ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault()); 

3。使用java.util.PropertyResourceBundle类的构造函数 
示例: 
InputStream in = new BufferedInputStream(new FileInputStream(name)); ResourceBundle rb = new PropertyResourceBundle(in); 

4。使用class变量的getResourceAsStream()方法 
示例: 
InputStream in = JProperties.class.getResourceAsStream(name); Properties p = new Properties(); p.load(in); 

5。使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法 
示例: 
InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name); Properties p = new Properties(); p.load(in); 

6。使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法 
示例: 
InputStream in = ClassLoader.getSystemResourceAsStream(name); Properties p = new Properties(); p.load(in); 

7.Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法 
示例:
InputStream in = context.getResourceAsStream(path); 
Properties p = new Properties(); 
p.load(in); 


如何从输入流中加载属性文件
使用load(InputStream is)方法:
Properties properties = new Properties();   
InputStream is = new FileInputStream("conn.properties");   
properties.load(is);   
is.close();  


如何读属性文件中的值
使用getProperties(String key)方法:
String temp = properties.getProperties(String key);
 
<注>重载的方法getProperties(String key, String default)方法 将在查询不到值的情况下,返回default.
即: 如果 null == properties.getProperties(String key);
则有 default == properties.getProperties(String key, String default);

如何获取属性文件中的所有的键
使用propertyNames()方法,该方法返回是键的枚举.
Enumeration enumeration = properties.propertyNames(); 
 

如何修改属性文件中的值
setProperties(String key, String value)

方法.
<注>该方法调用的 Hashtable 的put方法.如果键存在,则修改值;如果键不存在,则添加值.

如何存储属性文件到输出流
使用store(OutputStream os, String description)方法:
Properties properties = new Properties();   
OutputStream os = new FileOutputStream("test.properties");   
String description = "store properties to test.properties";   
properties.store(os, description);   
os.close();  


如何清空所有值
使用
clear()

方法.
<注>该方法继承自 Hashtable 的clear()方法.清空哈希表.

三.实例附件
<注>实例中没有指明properties文件的绝对路径.那么默认是在项目根目录下的.
当生成新文件时,使用F5刷新就能看见新文件产生了.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics