properties文件的读取

在项目中properties文件的读取是必不可少的,在这里写一个简单的例子

package filemanage;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;


public class PropertiesExample {

	public static void main(String[] args) {
		getPropertiesByKey("test.properties","username2");
	}
	/**
	 * 根据文件名和相应的key读取properties文件内容
	 * @param fileName
	 * @param key
	 * @return
	 */
	public static String getPropertiesByKey(String fileName,String key){
		String result = "";
		Map map=new HashMap(); 
		//test.properties放在src根目录下
		URL url = PropertiesExample.class.getClassLoader().getResource(fileName);
		//如果文件不存在就返回null
		if(url == null){
			System.out.println("文件不存在");
			return "文件不存在";
		}
		Properties p = new Properties();
		InputStream in = null;
		try {
			//直接通过getResourceAsStream得到文件流也可以使用new FileInputStream(new File("文件路径"))
			in = PropertiesExample.class.getClassLoader().getResourceAsStream(fileName);;
			p.load(in);
			result =  p.get(key).toString();
			/**************************读取properties文件中所有key和value并且把所有值都放在map中******************************************************************/
			//获得properties中所有的键放于枚举类型中! 
			Enumeration enu=p.keys(); 
			while(enu.hasMoreElements()){ 
				//获得一个keyStr 
				String keyStr=enu.nextElement().toString(); 
				//获得 该key 对应的  value 
				String value=p.getProperty(keyStr); 
				System.out.println(keyStr+"  "+value);
				//将 key 和 value 以utf-8的方式进行编码转换 ,经过测试,没有进行编码转换的是ok,所有需不需要进行转换得根据实际情况来看
				try { 
					keyStr = new String(key.getBytes("ISO8859-1"),"UTF-8"); 
					value = new String(value.getBytes("ISO8859-1"),"UTF-8"); 
					System.out.println(keyStr+"  "+value);
					//放入map 
					map.put(key,value); 
				} 
				catch (UnsupportedEncodingException e) { 
					System.out.println("编码失败!"); 
				} 
			}
			/********************************************************************************************/
		} 
		catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值