java.util.Properties的作用,,主要用于读取配置文件,Properties
继承于Hashtable.
常用的方法:
1. load(InputStream inStream)
:从输入流中读取属性列表(键和元素对);
2. load(Reader reader)
:按简单的面向行的格式从输入字符流中读取属性列表(键和元素对);
3. getProperty(String key)
: 用指定的键在此属性列表中搜索属性 ;
4. setProperty(String key,String value)
: 调用Hashtable 的方法 put;
5.
store(OutputStream out,String comments)
:以适合使用load(InputStream)
方法加载到Properties
表中的格式,将此Properties
表中的属性列表(键和元素对)写入输出流 ;
6.
store(Writer writer,String comments)
: 以适合使用load(Reader)
方法的格式,将此 Properties
表中的属性列表(键和元素对)写入输出字符。
示例:
(类名不建议使用中文, 这里是为了测试 ,给的名字)
public class 测试 {
public static void main(String[] args) throws Exception {
Properties pt=new Properties();
String lj=测试.class.getResource("/ceshi.properties").getPath();
String lj2=测试.class.getClassLoader().getResource("com/rui/test/测试.class").getPath();
System.out.println("url:"+lj);
//这里打印中文的时候, 已经 被URL编码了
System.out.println("url2(里打印中文的时候, 已经 被URL编码了):"+ lj2 );
System.out.println("url2(URL解码后):"+ new String (java.net.URLDecoder.decode( lj2 ).getBytes(),"utf-8"));
FileInputStream fis = new FileInputStream(lj);
pt.setProperty("ddd", "rrr");
pt.load(fis);
System.out.println(pt.getProperty("ceshi"));
System.out.println(pt.getProperty("ceshi2"));
System.out.println(pt.getProperty("ddd"));
FileOutputStream fos=new FileOutputStream("./ceshi.txt");
pt.store(fos, "there are comments");
fis.close();
fos.close();
}
}
ceshi.properties文件中的内容:
ceshi=this is
ceshi2=testData