使用property读取外部文件内容

package com.jdbc;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 使用property读取外部文件内容
* @author Administrator
*
*/
public class GetPropertyUtil {
private static Properties property=null;
static{
try {

//此处注意:GetPropertyUtil.class.getResource(".").getPath()中可以使用GetPropertyUtil.class.getResource(".").getFile();两者表示含义一样,都是获取到当前类所在的全路径,指向当前类所在的包下。getResource("."):表示获取当前所在的文件路径,改为getResource(" ")也可以,表示含义一样。改为getResource("/")表示跳出当前包,从跟路径下读取路径。
String currentPath=GetPropertyUtil.class.getResource(".").getPath();

//String currentPath=GetPropertyUtil.class.getResource(".").getFile();
InputStream in=new FileInputStream(new File(currentPath+"db.property"));
property=new Properties();
property.load(in);
} catch (FileNotFoundException e) {

} catch (IOException e) {

System.out.println(e.getMessage());
}
}
/* 根据Key 读取Value */
public static String getValue(String key) {
if(property.containsKey(key)){
return property.getProperty(key);
}else{
return null;
}

}
public static void main(String[] args) {
String driver=getValue("db.Driver");
String url=getValue("db.URL");
String user=getValue("db.USER_NAME");
String pass=getValue("db.PASS_WORD");
System.out.println(driver);
System.out.println(url);
System.out.println(user);
System.out.println(pass);

}
}

posted @ 2017-07-14 13:04  磕磕碰碰后才知道如何改变  阅读(511)  评论(0编辑  收藏  举报