zoukankan      html  css  js  c++  java
  • properties文件读取与写入

    将peoperties文件的读取和写入封装成了一个工具类:

    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Properties;
    import java.util.Set;
    
    public class PropertyUtil {
    
    	/**
    	 * 读取properties文件
    	 * @param fileName
    	 * @return
    	 */
    	public static Map<String, String> getProperties(String fileName) {
    		Map<String, String> propertyMap = new HashMap<String, String>();
    		Properties properties = new Properties();
    		InputStream in = null;
    		try {
    			in = new BufferedInputStream(new FileInputStream(fileName));
    			properties.load(in);
    			Iterator<String> itr = properties.stringPropertyNames().iterator();
    			while (itr.hasNext()) {
    				String key = itr.next();
    				String value = properties.getProperty(key);
    				propertyMap.put(key, value);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (null != in) {
    				try {
    					in.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return propertyMap;
    	}
    
    	/**
    	 * 将properties保存成文件
    	 * @param properties
    	 * @param fileName
    	 * @param comments
    	 */
    	public static void saveProperties(Map<String, String> properties,
    			String fileName, String comments) {
    		Properties property = new Properties();
    		FileOutputStream out = null;
    		try {
    			out = new FileOutputStream(fileName);
    			Set<Map.Entry<String, String>> entrySet = properties.entrySet();
    			for (Map.Entry<String, String> entry : entrySet) {
    				String key = entry.getKey();
    				String value = entry.getValue();
    				property.setProperty(key, value);
    			}
    			property.store(out, comments);
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			if (null != out) {
    				try {
    					out.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    
    }
    
  • 相关阅读:
    如何解除任务管理器被禁用
    一、JavaScript概述
    001_html基本结构
    postman常见问题记录
    fidder工具使用
    SonarQube工具使用问题汇总
    业余书籍读后感
    jmater常见问题处理
    测试知识记录(更新中)
    HTTP协议
  • 原文地址:https://www.cnblogs.com/acode/p/7169642.html
Copyright © 2011-2022 走看看