Java中Properties文件读取工具类

来源:互联网 发布:软件著作权登记公告 编辑:程序博客网 时间:2024/05/23 19:54

PropertiesUtils属性文件读取工具类

/**

 * 读取属性文件内容

 *

 */

public class PropertiesUtils {

publicstatic final String OrgPropertiesName"baidu.properties";

publicstatic final StringORG_ID"baidu_id";

publicstatic final StringORG_NAME"baidu_name";


/**

* 读取属性文件中的值

* @param propertiesFileName属性文件名称在classPath目录下

* @param key属性文件中定义的key

* @return

* @throws IOException 

* @throws FileNotFoundException 

*/

public static String getValue(String propertiesFileName, Stringkey) throws FileNotFoundException, IOException{

//通过文件名读取类路径下的属性文件

ClassPathResource cp = new ClassPathResource(propertiesFileName);

Properties props =new Properties();

//读取属性文件输入流

InputStream in =new BufferedInputStream(new FileInputStream(cp.getFile()));

//将输入流加载到属性对象中

props.load(in);

in.close();

//通过key在属性对象中读取值

return props.getProperty(key);

}

/**

* 获取属性文件对象,该对象可以重复使用,而不是每次都读取流操作

* @param propertiesFileName

* @return

* @throws FileNotFoundException

* @throws IOException

*/

public static Properties getProperties(String propertiesFileName)throws FileNotFoundException, IOException{

ClassPathResource cp = new ClassPathResource(propertiesFileName);

Properties props =new Properties();

InputStream in =new BufferedInputStream(new FileInputStream(cp.getFile()));

props.load(in);

in.close();

returnprops;

}

/**

* 通过属性文件对象获取value

* @param props属性文件对象

* @param key属性文件key

* @return

*/

public static String getValue(Properties props, Stringkey){

return props.getProperty(key);

}

}



原创粉丝点击