`
shiguili505116
  • 浏览: 64568 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类

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

    博客分类:
  • java
阅读更多
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;

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;
 }
 
 public String getValue(String key) {
  if (pro.containsKey(key)) {
   String value = pro.getProperty(key);
   return value;
  } else {
   return "";
  }
 }

 
 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
  

 

 

 

 

 

 

 

 

 

 

 

 

 
 
 
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics