关于java中Properties类的简单的使用例子

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值