最近在写一个项目,涉及到很多的基本数据,比如网站标题,网站每页显示条数等等,之前的项目都是使用的 数据库 存放的原则,但是后来想想,这些数据可能很少会出现修改,所有就想着,直接用一个配置文件就可以搞定。然后就自己琢磨了一下,下面上方案

首先看一下我的文件目录

其中两个绿色的,一个是 webseting.properties 一个是 WebSettingUtil.java

 

我们先写一下配置文件的内容

xxx=222
zzz=333
yyy=111

下面是一个公共类

package com.bihucms.ssm.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
/**
 * Created by benhailong on 2017/10/4.
 */
public class WebSettingUtil {
    // 读取文件
    public static Map<String,String> read(String path){

        Map<String,String> webset = new HashMap<String,String>();

        Properties prop = new Properties();
        try{
            //读取属性文件a.properties
            InputStream in = new BufferedInputStream (new FileInputStream(path));
            prop.load(in);     ///加载属性列表
            Iterator<String> it = prop.stringPropertyNames().iterator();
            while(it.hasNext()){
                String key=it.next();
                webset.put(key,prop.getProperty(key));
            }
            in.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
        return webset;
    }
    
    // 修改
    // 必须把原有的参数全部带全,否则会出现读取错误
    public static void write(Map<String,String> map,String path,String note){
        Properties prop = new Properties();
        try{
            ///保存属性到 配置文件
            FileOutputStream oFile = new FileOutputStream(path, false);//true表示追加打开 false标识重写
            for (Map.Entry<String,String> entry : map.entrySet()) {
                prop.setProperty(entry.getKey(),entry.getValue());
            }
            prop.store(oFile, note);
            oFile.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
    }
}

调用的时候

public static void main(String[] args) {
    String path = "src/main/resources/webseting.properties";
    // 读取文件
    //    Map<String,String> webset = read();
    //    System.out.println("读取到的:"+webset.get("setingDays"));
    // 写入配置文件
    Map<String,String> webset = new HashMap<String,String>();
    webset.put("yyy","111");
    webset.put("xxx","222");
    webset.put("zzz","333");
    write(webset,path,"这里是备注");
}

其他的类的调用方法一样

public static void main(String[] args) {
    String path = "src/main/resources/webseting.properties";
    Map<String,String> webset = WebSettingUtil.read(path);
    System.out.println("读取到的:"+webset.get("xxx"));
    System.out.println("读取到的:"+webset.get("yyy"));
    System.out.println("读取到的:"+webset.get("zzz"));
}

看结果