论坛首页 Java企业应用论坛

Java读取本地文件 propertie文件

浏览 9928 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (2) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-04-26  

如本地存放文件:ad.properties

里面的内容为:lev1=001,002,003,004,

lev2=005,007,

lev3=002,003

新建java JProperties.java

package com.bjsoft.util;

import org.apache.log4j.Logger;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Properties;

/**
 * 该类主要作用为读取本地propertie文件
 * @author Administrator
 */
public class JProperties {
	private static final Logger logger = Logger.getLogger(JProperties.class);

	private Properties propertie;
	private FileInputStream inputFile;
	
	/**
	 * 初始化JProperties 类
	 */
	public JProperties(){
		propertie = new Properties();
	}
	
	/**
	 * 初始化JProperties 类
	 * 加载本地文件
	 * @param filePath	文件存储路径
	 */
	public JProperties(String filePath){
		propertie = new Properties();
		try{
			inputFile = new FileInputStream(filePath);
			propertie.load(inputFile);
			inputFile.close();
		}catch (Exception  e) {
			// TODO: handle exception
			logger.info("读取属性文件--->失败!- 原因:文件路径错误或者文件不存在");
			e.printStackTrace();
		}
	}
	
	/**
	 * 返回要获取的值
	 * @return key
	 */
	public String getValue(String key){
		if(propertie.containsKey(key)){
			String value = propertie.getProperty(key);			//得到某属性的值
			return value;
		}else{
			return "";
		}
	}
	
	/**
	 * 重载函数 得到key的值 value
	 * @param fileName	propertie文件的路径+文件名
	 * @param key	得到其值的键	
	 * @return value	key的值
	 */
	public String getValue(String fileName, String key){
		try{
			String value = "";
			inputFile =  new FileInputStream(fileName);
			propertie.load(inputFile);
			inputFile.close();
			if(propertie.containsKey(key)){
				value = propertie.getProperty(key);
				return value;
			}else{
				return "";
			}
		}catch (Exception e) {
			logger.info("读取属性文件--->失败!- 原因:文件路径错误或者文件不存在");
			e.printStackTrace();
			return "";
		}
		
	}
		
	/**
	 * 清除propertie文件所有的key值
	 */
	public void clear(){
		propertie.clear();
	}	
}

 

测试运行效果:TestJP.java

package com.bjsoft.util;

import java.util.ArrayList;

public class TestJP {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		JProperties jp = new JProperties("D:\\java\\webapps\\ip\\ipv6\\ad.properties");
		String ad1 = jp.getValue("lev1");
		String ad2 = jp.getValue("lev2");
		System.out.println("广告1的值:"+ad1+",广告的长度:"+ad1.length());
		System.out.println("广告2的值:"+ad2+",广告的长度:"+ad2.length());
	}
}

 

   发表时间:2013-04-26  
要是读web 下的文件呢
0 请登录后投票
   发表时间:2013-04-27  
每用到一次就得读一下文件。
0 请登录后投票
   发表时间:2013-04-27  
lc32781971 写道
每用到一次就得读一下文件。

可以用单列实现
0 请登录后投票
   发表时间:2013-04-27  
发下原来写的。

public class ConfigUtil {

	private static String SERVICE_CODE_FILE = "config.properties" ;
	
	private static Properties pro = null;
	
	public static Logger logger = Logger.getLogger(ConfigUtil.class);
	
	/**
	 * 读取配置文件取到相应的值
	 * @param configFile 配置文件名称
	 * @param key 
	 * @return
	 */
	public static String getServiceId(String configFile,String key){
		String value = null;
		try {
			Properties properties = new Properties();
			properties.load(ConfigUtil.class.getClassLoader().getResourceAsStream(configFile));
			value = properties.getProperty(key);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return value ;
	}
	
	/**
	 * 取properties文件中的值
	 * @param key 键
	 * @return
	 */
	public static String getServiceId(String key){
		String value = null ;
		try {
			if(pro==null){
				pro = new Properties();
				synchronized (pro) {
					pro.load(ConfigUtil.class.getClassLoader().getResourceAsStream(SERVICE_CODE_FILE));
				}
			}
			value = pro.getProperty(key);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return value;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(ConfigUtil.getServiceId("801002"));
	}

}
0 请登录后投票
   发表时间:2013-04-30  
楼主贴出来的代码,代码质量要有严格的把关,比如:关闭流放在 finally中,要不然就是误人子弟。
个人意见,不喜轻喷
0 请登录后投票
   发表时间:2013-04-30  
lohasle 写道
要是读web 下的文件呢

建议去看下spring是怎么做的
0 请登录后投票
   发表时间:2013-05-01  
hekuilove 写道
lohasle 写道
要是读web 下的文件呢

建议去看下spring是怎么做的


读取web下的配置文件也是差不多的,关键是获取到文件路径。
可以用 System.getProperty()
或者 class.getClassLoader().getResource()
0 请登录后投票
   发表时间:2013-05-01  
楼主这段代码,还可以再优化一下。

1.如加载配置文件时,可以catch FileNotFoundException,提示文件找不到,其他Exception是文件内容错误。


2.在getValue(String key) 方法中,可以加多一个重载:
getValue(String key, String defaultValue)
在没有key这个属性的情况下,返回 defaultValue

个人意见哈
0 请登录后投票
   发表时间:2013-05-01  
hekuilove 写道
lohasle 写道
要是读web 下的文件呢

建议去看下spring是怎么做的


Spring
String CLASSPATH_URL_PREFIX = “classPath”;
public Resource getResource(String location) {
          Assert.notNull(location, "Location must not be null");
          if (location.startsWith(CLASSPATH_URL_PREFIX)) {
               return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
          }
          else {
               try {
                    // Try to parse the location as a URL...
                    URL url = new URL(location);
                    return new UrlResource(url);
               }
               catch (MalformedURLException ex) {
                    // No URL -> resolve as resource path.
                    return getResourceByPath(location);
               }
          }
     }



其实就是通过ClassLoad.getResource得到的
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics