java读写properties文件,解决系统找不到指定路径,解决写入后读取正常,但文件数据未更新问题

来源:互联网 发布:网站接入微信支付源码 编辑:程序博客网 时间:2024/06/06 22:14
properties属性文件:config.properties
#
#Tue Aug 13 15:30:56 CST 2013
timeInterval=33
name=holdOn
filepath=bb
ip=192.168.1.1
 
 
类实例:Configuration.java 

package example;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * 读取properties配置文件
 */
public class Configuration {
 private Properties pro;
 private FileInputStream fileInputStream;
 private FileOutputStream fileOutputStream;
 private String filepath;

 public Configuration() {
  
        //重要内容


        //测试地址
  filepath="D:\\config.properties";
  
  pro = new Properties();
  try {
   fileInputStream = new FileInputStream(filepath);
   pro.load(fileInputStream);
   fileInputStream.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

 /**
  * 得到文件路径
  */
 public String getfilepath() {
  return filepath;
 }

 /**
  * 根据key取得键值
  */
 public String getValue(String key) {
  if (pro.containsKey(key)) {
   String value = pro.getProperty(key);
   return value;
  } else {
   return "";
  }
 }


 /**
  * 改变或者添加一个key的值
  * 当key存在于properties文件中时,修改key的值, 当key不存在时,添加键值对
  * @param key:要存入的键
  * @param value:要存入的值
  */
 public void setValue(String key, String value) {
  pro.setProperty(key, value);
 }

 /**
  * 将更改后的文件数据存入指定的文件中
  */
 public void saveFile(String fileName,String comments) {
  try {
   fileOutputStream = new FileOutputStream(fileName);
   pro.store(fileOutputStream, "");
   fileOutputStream.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException ioe) {
   ioe.printStackTrace();
  }
 }

 /**
  * 测试方法
  */
 public static void main(String[] args) {
  
  String filename="D:\\config.properties";
  Configuration conf = new Configuration();
  
  conf.setValue("timeInterval","33");
  conf.setValue("filepath","bb");
  conf.saveFile(filename,"test");
  
  String timeInterval= conf.getValue("timeInterval");
  System.out.println(timeInterval);
  String filepath = conf.getValue("filepath");
  System.out.println(filepath);
  

 }
}

 

提示:实例可以正常运行,重要内容(获取项目中properties文件路径)被省略,可能是您需要的,有需要的,给我发邮件,我把完整java实例打包回发给您。
我的邮箱:qmys116505@qq.com

 

 

 

 

原创粉丝点击