`

文件存储配置信息增 改 删 查

阅读更多

本示例以properties格式文件为主

如果你自己想要其他格式的文件如txt等等,可以自己修改代码

如果你想要自己的解析格式也可以修改conf代码中的parseLine方法里的解析格式

1.配置文件:bsidinfo.properties

###gsmconf 存储短信发送配置信息,message:发送命令内容,comid=COM2端口号大写,baud=115200为短信设备的波特率,根据需求修改####
[gsmconf]
message=SMS:SET+WAKEUP
comid=COM3
baud=9600
###connectioninfo连接流媒体服务器的配置信息,IP、端口号port、用户名username 密码password,根据需求修改##
[connectioninfo]
port=7660
username=root
password=6973hiktb
ip=202.91.248.243

###以下是所有终端的配置信息,[]里代表的是终端的名称不能重复,bsid终端id号,simid手机号,status默认为0##
##这里你可以添加、修改、删除、任何终端,但是请慎重处理
[红满线85号塔_1013]
bsid=000001013
simid=15349919673
status=0
[3G-000001143]
bsid=000001143
simid=13396716823
status=0

 

2.代码:

   Conf.java

  

package cn.thunderbird.lm.media.util.conf;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

/**
 * 该类主要解析example.propertes文件
 * 格式:
 * #####是注释
 * [content]
 * key=value;
 * @author luqw
 */
public class Conf {
	private static final Logger log = Logger.getLogger(Conf.class);
	private static final ArrayList String = null;
	//all the node of properties will be restored.Every object type is ConfEntity class.
	private ArrayList nodeList = null;
	private String filePath = null;
	private Map current_map = null;
	private ConfEntity current_Entity = null;
	public Conf() {
	}
	/**
	 * 首先导入文件
	 * @param filePath
	 * @throws Exception
	 */
	public void importConf(String filePath) {
		RandomAccessFile randFile = null;
		try {
			this.filePath = filePath;
			randFile = new RandomAccessFile(filePath, "r");
		} catch (FileNotFoundException e) {
			closeRandomFile(randFile);
			System.out.println(Constant.E_OprConfigFileError
					+ filePath);
		}
		try {
			loadNodeList(randFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 *  */
	public void moveBak() {
		try {
			File destFile = new File(this.filePath);
			File bakFile = new File(this.filePath + ".bak");
			if (destFile.exists()) {
				destFile.delete();
			}
			bakFile.renameTo(destFile);
		} catch (Exception e) {
			System.out.println("move bak file[" + this.filePath
					+ ".bak] to oraginal file" + this.filePath + "] error:"
					+ e.getMessage());
		}
	}
	/**
	 * @throws Exception
	 */
	public void deleteBak() {
		try {
			File bakFile = new File(this.filePath + ".bak");
			if (bakFile.exists()) {
				bakFile.delete();
			}
		} catch (Exception e) {
			System.out.println("delete bak file[" + this.filePath
					+ ".bak] error:" + e.getMessage());
		}
	}
	/**
	 * @param rf
	 */
	public void closeRandomFile(RandomAccessFile rf) {
		try {
			if (rf != null) {
				rf.close();
			}
		} catch (Exception e) {
			System.out
					.println("close randomAccessFile error:" + e.getMessage());
		}
	}
	/**
	 * export and restore
	 **/
	public void exportConf() {
		RandomAccessFile rf = null;
		if (nodeList != null) {
			try {
				File oraFile = new File(this.filePath);
				File bakFile = new File(this.filePath + ".bak");
				if (bakFile.exists()) {
					bakFile.delete();
				}
				oraFile.renameTo(bakFile);
				rf = new RandomAccessFile(this.filePath, "rw");
				rf.seek(rf.length());
				Iterator it = nodeList.iterator();
				boolean isFirstLine = true;
				while (it.hasNext()) {
					ConfEntity entity = (ConfEntity) it.next();
					Map map = entity.getMap();
					String nodeName = "[" + entity.getNodeName() + "]";
					if (isFirstLine) {
						isFirstLine = false;
					} else {
						nodeName = "\n" + nodeName;
					}
					rf.writeBytes(nodeName);
					if ((map != null) && (map.size() > 0)) {
						Iterator tt = map.keySet().iterator();
						while (tt.hasNext()) {
							String key = (String) tt.next();
							String value = (String) map.get(key);
							String line = "\n" + key + "=" + value;
							rf.writeBytes(line);
						}
					}
				}
				deleteBak(); //
			} catch (Exception e) {
				moveBak(); //
				System.out.println(Constant.E_OprConfigFileError
						+this.filePath
						+ e.getMessage());
			} finally {
				closeRandomFile(rf);
			}
		}
	}
	/**
	 * 载入文件里面的信息
	 * @param randFile
	 * @throws Exception
	 */
	public void loadNodeList(RandomAccessFile randFile) throws Exception {
		if (randFile != null) {
			try {
				String str;
				nodeList = new ArrayList();
				while ((str = randFile.readLine()) != null) {
					String strLine = str;
					parseLine(strLine);
				}
				if (current_Entity != null) {
					current_Entity.setMap(current_map);
					nodeList.add(current_Entity);
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println(Constant.E_OprConfigFileError
						 + this.filePath);
			} finally {
				closeRandomFile(randFile);
			}
		}
	}
	/**
	 * 按照prperties文档格式解析文件
	 * #代表注释 不解析
	 * []解析
	 * @param lineStr
	 */
	public void parseLine(String lineStr) {
		if ((lineStr != null) && (lineStr.length() > 0)
				&& !lineStr.startsWith("#")) {
			if (lineStr.startsWith("[")) {
				// a new node
				if (current_Entity != null) {
					current_Entity.setMap(current_map);
					nodeList.add(current_Entity);
				}
				current_Entity = new ConfEntity();
				String nodeName = lineStr.substring(1, lineStr.length() - 1);
				current_Entity.setNodeName(nodeName);
				current_map = new HashMap();
			} else {
				if (lineStr.contains("=")) {
					String key = "";
					String value = "";
					int indexOfEq = lineStr.indexOf("=");
					key = lineStr.substring(0, indexOfEq);

					if ((lineStr.length() - 1) > indexOfEq) {
						value = lineStr.substring(indexOfEq + 1, lineStr
								.length());
					}
					current_map.put(key, value);
				}
			}
		}
	}
	/**
	 * getValue by node name and property key
	 * @param node
	 * @param key
	 * @return
	 */
	public String getValue(String node, String key) {
		String value = null;
		if ((nodeList != null) && (nodeList.size() > 0)) {
			Iterator it = nodeList.iterator();
			while (it.hasNext()) {
				ConfEntity entity = (ConfEntity) it.next();
				if (entity.getNodeName().equals(node)) {
					Map map = entity.getMap();
					if (map != null) {
						value = (String) map.get(key);
						break;
					}
				}
			}
		}
		return value;
	}
	/**
	 * 
	 * @param nodeName
	 * @throws Exception
	 */
	public void addNode(String nodeName) {
		if (nodeName != null) {
			if ((nodeList != null) && (nodeList.size() > 0)) {
				boolean hasNode = false; //
				Iterator it = nodeList.iterator();
				while (it.hasNext()) {
					ConfEntity entity = (ConfEntity) it.next();
					if (entity.getNodeName().equals(nodeName)) {
						hasNode = true;
						break;
					}
				}
				if (!hasNode) {
					ConfEntity entity = new ConfEntity();
					entity.setNodeName(nodeName);
					entity.setMap(null);
					nodeList.add(entity);
				}
			}
		}
	}

	/**
	 * @param nodeName
	 * @param key
	 * @param value
	 * @throws Exception
	 */
	public void addPropertie(String nodeName, String key, String value) {
		if (nodeName != null) {
			if ((nodeList != null) && (nodeList.size() > 0)) {
				boolean hasNode = false;
				Iterator it = nodeList.iterator();
				ConfEntity entity = null;
				while (it.hasNext()) {
					ConfEntity tempEntity = (ConfEntity) it.next();
					if (tempEntity.getNodeName().equals(nodeName)) {
						hasNode = true;
						entity = tempEntity;
						break;
					}
				}
				if (!hasNode) {
					entity = new ConfEntity();
					entity.setNodeName(nodeName);
					Map map = new HashMap();
					map.put(key, value);
					entity.setMap(map);
					nodeList.add(entity);
				} else {
					Map map = entity.getMap();
					if (map == null) {
						map = new HashMap();
					}
					map.put(key, value);
					entity.setMap(map);
				}
			}
		}
	}
	/**
	 *  
	 * @param nodeName
	 * @param map
	 * @throws Exception
	 */
	public void addPropertie(String nodeName, Map map) {
		if ((nodeName != null)) {
			if ((nodeList != null) && (nodeList.size() > 0)) {
				boolean hasNode = false;
				Iterator it = nodeList.iterator();
				ConfEntity entity = null;
				while (it.hasNext()) {
					ConfEntity tempEntity = (ConfEntity) it.next();
					if (tempEntity.getNodeName().equals(nodeName)) {
						hasNode = true;
						entity = tempEntity;
						break;
					}
				}
				if (!hasNode) {
					System.out.println("!hasNode");
					entity = new ConfEntity();
					entity.setNodeName(nodeName);
					entity.setMap(map);
					nodeList.add(entity);
				} else {
					Map oraMap = entity.getMap();
					if ((oraMap == null) || (oraMap.size() == 0)) {
						System.out.println("oraMap == null");
						oraMap = map;
					} else {
						Iterator mapIt = map.keySet().iterator();
						while (mapIt.hasNext()) {
							String key = (String) mapIt.next();
							String value = (String) map.get(key);
							oraMap.put(key, value);
						}
					}
				}
			}
		}
	}

	/**
	 * 
	 * @param nodeName
	 * @throws Exception
	 */
	public void removeNode(String nodeName) {
		if (nodeName != null) {
			if ((nodeList != null) && (nodeList.size() > 0)) {
				boolean hasNode = false;
				Iterator it = nodeList.iterator();
				while (it.hasNext()) {
					ConfEntity entity = (ConfEntity) it.next();
					if (entity.getNodeName().equals(nodeName)) {
						nodeList.remove(entity);
						break;
					}
				}
			}
		}
	}

	/**
	 * 
	 * @param nodeName
	 * @param key
	 */
	public void removeKey(String nodeName, String key) {
		if ((nodeName != null) && (key != null)) {
			if ((nodeList != null) && (nodeList.size() > 0)) {
				Iterator it = nodeList.iterator();
				while (it.hasNext()) {
					ConfEntity entity = (ConfEntity) it.next();
					if (entity.getNodeName().equals(nodeName)) {
						Map map = entity.getMap();
						map.remove(key);
						break;
					}
				}
			}
		}
	}
	/**
	 * @param nodeName
	 * @param key
	 * @param value
	 */
	public void setProperties(String nodeName, String key, String value) {
		if ((nodeName != null) && (key != null) && (key.length() > 0)
				&& (value != null)) {
			if ((nodeList != null) && (nodeList.size() > 0)) {
				Iterator it = nodeList.iterator();
				while (it.hasNext()) {
					ConfEntity entity = (ConfEntity) it.next();
					if (entity.getNodeName().equals(nodeName)) {
						ConfEntity confEntity = new ConfEntity();
						Map map = entity.getMap();
						map.remove(key);
						map.put(key, value);
						break;
					}
				}
			}
		}
	}
	/**
	 *  
	 * @param nodeName
	 * @param key
	 * @param value
	 */
	public List<String> listKey(String nodeName) {
		ArrayList<String> nodeLists = new ArrayList<String>();
		if ((nodeList != null) && (nodeList.size() > 0)) {
			Iterator it = nodeList.iterator();
			while (it.hasNext()) {
				ConfEntity entity = (ConfEntity) it.next();
				if (entity.getNodeName().equals(nodeName)) {
					Map map = entity.getMap();
					if ((map != null) && (map.size() > 0)) {
						Iterator tt = map.keySet().iterator();
						while (tt.hasNext()) {
							String key = (String) tt.next();
							nodeLists.add(key);
						}
					}
				}
			}
		}
		return nodeLists;
	}
	public ArrayList getNodeList() {
		return nodeList;
	}

	/**
	 * 测试代码
	 */
	public void printNodeList() {
		if ((nodeList != null) && (nodeList.size() > 0)) {
			Iterator it = nodeList.iterator();
			while (it.hasNext()) {
				ConfEntity entity = (ConfEntity) it.next();
				System.out.println("---===========node===========---"
						+ entity.getNodeName());
				Map map = entity.getMap();
				if ((map != null) && (map.size() > 0)) {
					Iterator tt = map.keySet().iterator();
					while (tt.hasNext()) {
						String key = (String) tt.next();
						String value = (String) map.get(key);
						System.out.println(key + "-------->" + value);
					}
				}
			}
		}
	}

}

 

 

ConfEntity.java

package cn.thunderbird.lm.media.util.conf;
import java.util.Map;
public class ConfEntity {
 private String nodeName;
 private Map map;
 public String getNodeName() {
  return nodeName;
 }
 public void setNodeName(String nodeName) {
  this.nodeName = nodeName;
 }
 public Map getMap() {
  return map;
 }
 public void setMap(Map map) {
  this.map = map;
 }

 

Constant.java

package cn.thunderbird.lm.media.util.conf;
public class Constant {
	public static final String E_OprConfigFileError = "读写配置文件失败";
}

 

 

Test.java

 

package cn.thunderbird.lm.media.dao;
import java.util.Iterator;
import java.util.Map;
import cn.thunderbird.lm.media.util.CharacterUtil;
import cn.thunderbird.lm.media.util.conf.Conf;
public class Test {
	private static Conf conf =null;//全局的每次用完清空
	private static String filepath="";
	
	public  void addNode(String nodeName, Map map){
		 nodeName=CharacterUtil.utfToIsso(nodeName);
			 conf=new Conf();
			 conf.importConf(filepath);
			if ((map != null) && (map.size() > 0)) {
				Iterator tt = map.keySet().iterator();
				while (tt.hasNext()) {
					String key = (String) tt.next();
					String value = (String) map.get(key);
					conf.addPropertie(nodeName, key, value);
			}
			conf.exportConf();
			conf=null;
		 }
	}
	 public  void updateNode(String nodeName, Map map){
		 nodeName=CharacterUtil.utfToIsso(nodeName);
			 conf=new Conf();
			 conf.importConf(filepath);
			if ((map != null) && (map.size() > 0)) {
				Iterator tt = map.keySet().iterator();
				while (tt.hasNext()) {
					String key = (String) tt.next();
					String value = (String) map.get(key);
					conf.setProperties(nodeName, key, value);
				}
			}
			conf.exportConf();
			conf=null;
		}
	 //修改某一个属性
	 public  void updateProperty(String nodeName, String key,String value){
		 //nodeName=CharacterUtil.utfToIsso(nodeName);
			 conf=new Conf();
			 conf.importConf(filepath);
			 conf.setProperties(nodeName, key, value);
			 conf.exportConf();
			conf=null;
		}
	 public static void main(String[] args) {
		 Test test=new Test();
		filepath="D:\\conf\\bsidinfo.properties";
		test.updateProperty("test4","bsid","4");
		//其他的方法类似 map就是[]下面的名值对key=value
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics