Properties 文件的简单操作

properties 文件里面主要 存 一个Key对应一个Value  一般用来存放账户密码资料

方法有:Properties p=new  Properties();

           p.setproperty("key","value"); //存放 数据

     p.getProperty("key");//根据键值的到对象

           p.load(new FileInputStream(file)); //加载本地文件里的值

存在文件中的:

FileOutputStream d =new FileOutStream(file);

p.store(d,null);

*修改时如果键值(key)一样 则覆盖!

例子

1.根据Key读取Value

 1  public static String readValue(String filePath,String key) {
 2   Properties props = new Properties();
 3         try {
 4          InputStream in = new BufferedInputStream (new FileInputStream(filePath));
 5          props.load(in);
 6          String value = props.getProperty (key);
 7             System.out.println(key+value);
 8             return value;
 9         } catch (Exception e) {
10          e.printStackTrace();
11          return null;
12         }
13  }

 

2.读取propersties全部信息

 1  public static void readProperties(String filePath) {
 2      Properties props = new Properties();
 3         try {
 4          InputStream in = new BufferedInputStream (new FileInputStream(filePath));
 5          props.load(in);
 6             Enumeration en = props.propertyNames();
 7              while (en.hasMoreElements()) {
 8               String key = (String) en.nextElement();
 9                     String Property = props.getProperty (key);
10                     System.out.println(key+Property);
11                 }
12         } catch (Exception e) {
13          e.printStackTrace();
14         }
15     }

3.写入properties信息

 1   public static void writeProperties(String filePath,String parameterName,String parameterValue) {
 2      Properties prop = new Properties();
 3      try {
 4       InputStream fis = new FileInputStream(filePath);
 5             //从输入流中读取属性列表(键和元素对)
 6             prop.load(fis);
 7             //调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
 8             //强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
 9             OutputStream fos = new FileOutputStream(filePath);
10             prop.setProperty(parameterName, parameterValue);
11             //以适合使用 load 方法加载到 Properties 表中的格式,
12             //将此 Properties 表中的属性列表(键和元素对)写入输出流
13             prop.store(fos, "Update '" + parameterName + "' value");
14         } catch (IOException e) {
15          System.err.println("Visit "+filePath+" for updating "+parameterName+" value error");
16         }
17     }

 

 

转载于:https://www.cnblogs.com/Dreamlu/p/4037236.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值