java properties 属性_Java属性类:Properties的常用方法 | 学步园

Properties类本身是Hashtable类的子类,也是按照key-value的形式存放数据的.

设置和取得属性:

public class PropertiesDemo01{

public static void main(String args[]){

Properties pro = new Properties() ;// 创建Properties对象

pro.setProperty("BJ","BeiJing") ;// 设置属性

pro.setProperty("TJ","TianJin") ;

pro.setProperty("NJ","NanJing") ;

System.out.println("1、BJ属性存在:" + pro.getProperty("BJ")) ;

System.out.println("2、SC属性不存在:" + pro.getProperty("SC")) ;

System.out.println("3、SC属性不存在,同时设置显示的默认值:" + pro.getProperty("SC","没有发现")) ;

}

};

将属性保存到普通的属性文件中:

public class PropertiesDemo02{

public static void main(String args[]){

Properties pro = new Properties() ;// 创建Properties对象

pro.setProperty("BJ","BeiJing") ;// 设置属性

pro.setProperty("TJ","TianJin") ;

pro.setProperty("NJ","NanJing") ;

File file = new File("D:" + File.separator + "area.properteis") ;// 指定要操作的文件

try{

pro.store(new FileOutputStream(file),"Area Info") ;// 保存属性到普通文件

}catch(FileNotFoundException e){

e.printStackTrace() ;

}catch(IOException e){

e.printStackTrace() ;

}

}

};

从属性文件中读取内容:

public class PropertiesDemo03{

public static void main(String args[]){

Properties pro = new Properties() ;// 创建Properties对象

File file = new File("D:" + File.separator + "area.properteis") ;// 指定要操作的文件

try{

pro.load(new FileInputStream(file)) ;// 读取属性文件

}catch(FileNotFoundException e){

e.printStackTrace() ;

}catch(IOException e){

e.printStackTrace() ;

}

System.out.println("1、BJ属性存在:" + pro.getProperty("BJ")) ;

System.out.println("2、SH属性存在:" + pro.getProperty("SH")) ;

}

};

将属性保存在XML文件中:

public class PropertiesDemo04{

public static void main(String args[]){

Properties pro = new Properties() ;// 创建Properties对象

pro.setProperty("BJ","BeiJing") ;// 设置属性

pro.setProperty("TJ","TianJin") ;

pro.setProperty("NJ","NanJing") ;

File file = new File("D:" + File.separator + "area.xml") ;// 指定要操作的文件

try{

pro.storeToXML(new FileOutputStream(file),"Area Info") ;// 保存属性到普通文件

}catch(FileNotFoundException e){

e.printStackTrace() ;

}catch(IOException e){

e.printStackTrace() ;

}

}

};

从XML文件中读取属性:

public class PropertiesDemo05{

public static void main(String args[]){

Properties pro = new Properties() ;// 创建Properties对象

File file = new File("D:" + File.separator + "area.xml") ;// 指定要操作的文件

try{

pro.loadFromXML(new FileInputStream(file)) ;// 读取属性文件

}catch(FileNotFoundException e){

e.printStackTrace() ;

}catch(IOException e){

e.printStackTrace() ;

}

System.out.println("1、BJ属性存在:" + pro.getProperty("BJ")) ;

}

};

44f25edc7f970f81818281110526b865.png

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值