码迷,mamicode.com
首页 > 编程语言 > 详细

java操作properties文件简单学习

时间:2015-01-08 15:43:19      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:java   properties   

  1. java操作properties文件的工具类简单封装:


    注意:由于本地和环境和linux服务的路径有区别,或者jetty,resin,tomcat部署后,文件的路径也是有区别的。比如我们在linux上把项目放在另一个磁盘下,此时,文件的路径就是项目所在的路径,而不是WEB-INF下,所以,这里需要灵活配置!

  2. package com.sohu.util;
    
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Properties;
    import java.util.Set;
    
    import org.springframework.core.io.ClassPathResource;
    
    /**
     * 测试properties读写处理
     * @author liweihan ()
     * @version 1.0 (2015年1月6日 下午2:23:27)
     */
    public class TestProperties {
    	
    	/**
    	 * 说明:很多时候我们为了减轻数据库的压力,或者减少我们的服务的压力。
    	 * 对于不经常变的数据,我们可以放在配置文件中!
    	 * 
    	 *     
    	 *     containsKey()
    	 * 
    	 */
    	private static String PFILE = null;
    	public static final boolean OS_LINUX = "/".equals(File.separator);  
    	 static{
    	        Properties p = new Properties();
    	    	try {
    		        if(OS_LINUX) {
    		        	//方法1:
    		        	//p.load(TestProperties.class.getClassLoader().getResourceAsStream("config.properties"));
    		        	
    		        	//方法2:还可以用这个方法加载
    		        	p.load(new ClassPathResource("config.properties").getInputStream());
    		        	
    		        	//方法3:--应该用在具体路径的地方
    //		        	InputStream in = new BufferedInputStream(new FileInputStream("config.properties"));
    //		        	p.load(in);
    		        } else {
    		        	//方法1:
    		        	//p.load(TestProperties.class.getClassLoader().getResourceAsStream("config-windows.properties"));
    		        	
    		        	//方法2:
    		        	p.load(new ClassPathResource("config-windows.properties").getInputStream());
    		        	
    		        	//方法3:---应该用在具体路径的地方
    //		        	InputStream in = new BufferedInputStream(new FileInputStream("config-windows.properties"));
    //		        	p.load(in);
    		        	
    		        }
    		        PFILE = p.getProperty("goodsongPath").trim();
    	    	} catch (IOException e) {
    				e.printStackTrace();
    			} 
    	    }
    	
    
    	//属性文件全名
    //	private static final String PFILE = "D:\\liweiSohu\\workspaceForEclipse\\R20141229_han\\search-star-HDSS-STAR-WEB-F\\src\\main\\resources\\goodsong.properties";
    	//上面是windows系统本地测试,下面是linux系统
    //	private static final String PFILE = System.getProperty("user.dir") + File.separator + "goodsong.properties";
    	
    	//对应于属性文件的文件对象变量
    	private File m_file = null;
    	//属性文件的最后修改日期
    	private long m_lastModifiedTime = 0;
    	//属性文件所对应的属性对象变量
    	private Properties m_props = null;
    	
    	//本类可能存在的唯一的唯一实例
    	private static TestProperties m_instance = new TestProperties();
    	
    	/**
    	 * 私有构造方法,用以保证外界无法直接实例化
    	 */
    	private TestProperties() {
    		m_file = new File(PFILE);
    		m_lastModifiedTime = m_file.lastModified();
    		
    		if (m_lastModifiedTime == 0) {
    			System.err.println(PFILE + " file does not exist !");
    		}
    		m_props = new Properties();
    		try {
    			m_props.load(new FileInputStream(PFILE));
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    	
    	/**
    	 * 返回单一实例
    	 * @return
    	 * 
    	 * 2015年1月6日 下午2:58:02
    	 * liweihan
    	 */
    	public static synchronized TestProperties getInstance() {
    		System.out.println(" ---- :" + System.getProperty("user.dir"));
    		return m_instance;
    	}
    	
    	/**
    	 * 读取一特定的属性项
    	 * @param name		属性项的项名
    	 * @param defaultVal	属性项的默认值
    	 * @return	属性项的值(如果此项存在),默认值(如此项不存在)
    	 * 
    	 * 2015年1月6日 下午3:01:05
    	 * liweihan
    	 */
    	public Object getConfigItem(String name,Object defaultVal) {
    		long newTime = m_file.lastModified();
    		//检查属性文件是否被其他的程序修改过,如果是,重读此配置文件
    		if (newTime == 0) {
    			//属性文件不存在
    			if (m_lastModifiedTime == 0) {
    				System.err.println(PFILE + " file does not exist !");
    			} else {
    				System.err.println(PFILE + " file was deleted !");
    			}
    			
    			return defaultVal;
    		} else if (newTime > m_lastModifiedTime) {
    			//属性文件被修改过,重新加载配置文件
    			m_props.clear();
    			try {
    				m_props.load(new FileInputStream(PFILE));
    			}  catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
    		m_lastModifiedTime = newTime;
    		Object val = m_props.getProperty(name);
    		if (val == null) {
    			return defaultVal;
    		} else {
    			return val;
    		}
    	}
    	
    	/**
    	 * 根据指定的属性名获得属性值
    	 * @param itemName
    	 * @return
    	 * 
    	 * 2015年1月6日 下午3:39:55
    	 * liweihan
    	 */
    	public String getValue(String itemName) {
    		return m_props.getProperty(itemName);
    	}
     	
    	/**
    	 * 设置属性名和属性值[此设置并不能保存到配置文件中]
    	 * @param itemName
    	 * @param value
    	 * 
    	 * 2015年1月6日 下午3:45:08
    	 * liweihan
    	 */
    	public void setValue(String itemName,String value) {
    		m_props.setProperty(itemName, value);
    		return;
    	}
    	
    	/**
    	 * 保存配置文件,指定文件名和抬头描述
    	 * @param fileName
    	 * @param description
    	 * 
    	 * 2015年1月6日 下午3:56:09
    	 * liweihan
    	 * @throws Exception 
    	 */
    	public void saveFile(String fileName,String description) throws Exception {
    		try {
    			FileOutputStream fout = new FileOutputStream(fileName);
    			m_props.store(fout, description);//保存文件
    			fout.close();
    		} catch (Exception e) {
    			System.out.println("无法保存指定的配置文件:" + fileName);
    			throw new Exception("无法保存指定的配置文件:" + fileName);
    //			e.printStackTrace();
    		} 
    	}
    	
    	/**
    	 * 保存指定的配置文件
    	 * @param fileName
    	 * 
    	 * 2015年1月6日 下午3:59:04
    	 * liweihan
    	 * @throws Exception 
    	 */
    	public void saveFile(String fileName) throws Exception {
    		saveFile(fileName,"");
    	}
    	
    	/**
    	 * 保存指定文件,采用原有名字
    	 * 
    	 * 
    	 * 2015年1月6日 下午4:01:49
    	 * liweihan
    	 */
    	public void saveFile() throws Exception{
    		if (PFILE.length() == 0) {
    			throw new Exception(PFILE + " file does not exist !");
    		}
    		saveFile(PFILE);
    	}
    	
    	/**
    	 * 得到配置文件中所有的key和value值,并放在一个map结合中
    	 * @return
    	 * 
    	 * 2015年1月6日 下午4:50:39
    	 * liweihan
    	 */
    	public Map<String, String> getAllKeyAndValue() {
    		Map<String, String> map = new HashMap<String, String>();
    		
    		Enumeration en = m_props.propertyNames();
    		//遍历
    		while (en.hasMoreElements()) {
    			String key = en.nextElement().toString();//key值
    			String value = m_props.getProperty(key);
    			map.put(key, value);
    		}
    		return map;
    	}
    	
    	/**
    	 * 得到配置文件中所有的key和value值,并放在一个map结合中2
    	 * @return
    	 * 
    	 * 2015年1月7日 下午6:33:41
    	 * liweihan
    	 */
    	public Map<String, String> getAllKeyAndValue2() {
    		Map<String, String> map = new HashMap<String, String>();
    		
    		m_props.list(System.out);
    		Object[] objs = m_props.keySet().toArray();
    		for (int i = 0; i < objs.length; i++) {
    			map.put(objs[i].toString(), m_props.get(objs[i]).toString());
    		}
    		return map;
    	}
    	
    	public static void main(String[] args) {
    		
    		//1.获得java虚拟机的参数
    		Properties pps = System.getProperties();
    		pps.list(System.out);
    		
    	}
    	
    }

3.测试代码:

		TestProperties p = TestProperties.getInstance();
		String result = (String)p.getConfigItem(sid, "0");
		System.out.println("result:" + result);
		
		String result2 = p.getValue(sid);
		System.out.println("result2: " + result2);
		
/*		p.setValue("54418", "hanchao");
		p.setValue("20", "cc");*/
		p.setValue(key != null ? key : "0", value != null ? value : "0");

		try {
//			p.saveFile("system.conf","System.Global.Configuration");
			p.saveFile();
			if (key != null && value != null) {
				setStarIdAndSpaceIdToLocalCache();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		Map<String, String> map = p.getAllKeyAndValue2();
		for(Entry<String, String> en : map.entrySet()) {
			System.out.println("key:" + en.getKey() + ", value :" + en.getValue());
		}
		



* 参考:http://wenku.baidu.com/link?url=-02_xrVX1_OQn0a1EcGDQ-LYQ08QXkmVMHHJ7z_aliEkG_4orbP94fjdAf4V5em7PfNXISGbN1gmmRWWED_GrnEDAXWPEsCwCmrsDaUr82W


*     http://wenku.baidu.com/view/bbe96f6e25c52cc58bd6be99.html


*     http://www.cnblogs.com/bakari/p/3562244.html


*     

*     加载的六种方法:

*     http://blog.csdn.net/Senton/article/details/4083127



本文出自 “我的JAVA世界” 博客,请务必保留此出处http://hanchaohan.blog.51cto.com/2996417/1600546

java操作properties文件简单学习

标签:java   properties   

原文地址:http://hanchaohan.blog.51cto.com/2996417/1600546

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!