Java基础--Properties类操作.properties文件


一,读取properties文件内容参数。

  1. // 读取properties文件的值  
  2. public static void readProperties() {  
  3.     Properties properties = new Properties();  
  4.     File file = new File("file/read.properties");  
  5.     try {  
  6.         FileInputStream fis = new FileInputStream(file);  
  7.         properties.load(fis);  
  8.         Set<Object> keyset = properties.keySet();  
  9.         for (Object object : keyset) {  
  10.             System.out.println(object.toString() + ":"  
  11.                     + properties.getProperty(object.toString()));  
  12.         }  
  13.     } catch (FileNotFoundException e) {  
  14.         e.printStackTrace();  
  15.     } catch (IOException e) {  
  16.         e.printStackTrace();  
  17.     }  
  18. }  

解读:

1,创建持久属性集类properties。

2,创建文件类file并关联到项目名下file文件夹的properties文件read.properties文件。File类默认情况下查找工作目录下项目名下文件。如果加载的文件在其他磁盘下,需详细给集体目录,可是这样情况项目移植性很低,建议操作的文件都放在项目目录下。


3,创建文件输入流fis,关联到properties文件file。这里说一下文件输入流FileInputStream,和文件输出流FileOutStream,很多时候我们都会对文件输入流,输出流,写入流,读出流都很混淆,特别是对初学者。在IO操作中,我们的输入输出都是相对CPU来说的。输入流,我们要把外部文件读取并操作,所以文件相对CPU就是外部文件,要读进CUP所以用的是FileInputStream,输出流,把CPU中的内容写到文件中,相对CPU来说,数据是流出的,所以用的就是FileOutputStream。

4,properties.load(fis);属性集合类与文件输入流关联,往集合类中加载文件信息。

5,Set<Object> set = properties.keyset(); properties类继承HashTable,获取properties中的键集合。

6,属性保存在properties中是以键值对的形式保存的。循环语句根据键,获取properties中的值,实现读取.properties文件的功能。


二,写properties文件。

  1. // 写properties文件  
  2.     public static void writerProperties() {  
  3.         Properties properties = new Properties();  
  4.         File file = new File("file/wirte.properties");  
  5.         try {  
  6.             FileOutputStream fos = new FileOutputStream(file);  
  7.             properties.setProperty("name", "guo");  
  8.             properties.setProperty("password", "qinglao");  
  9.             properties.setProperty("value", "3");  
  10.             properties.setProperty("first", "郭");  
  11.             properties.store(fos, "保存文件");  
  12.         } catch (FileNotFoundException e) {  
  13.             e.printStackTrace();  
  14.         } catch (IOException e) {  
  15.             e.printStackTrace();  
  16.         }  
  17.     }  
解读:

1,Properties properties = new Properties();
File file = new File("file/wirte.properties");
FileOutputStream fos = new FileOutputStream(file); 这里的功能显而易见,创建Properties类,创建写入内容文件并关联文件输出流fileOutputStream。

2,properties是一个键值对集合,所以设置properties内容时是以键值对setProperties(key,value)形式,

3,properties.store(fos,"保存文件");把集合中的内容压到输出流中写进文件.实现写properties文件的功能

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值