关于properties

用eclipse 集成tomcat时,注意配置output的folder:



 


 在传统java类中,一般使用FileInputStream读取.properties 文件

FileInputStream in = new FileInputStream("/db.properties");
Properties prop = new Properties();
prop.load(in);
System.out.println(prop.getProperty("oracle-url"));

 FileInputStream 需要的是相对路径或是绝对路径。传统java类中,相对路径的根目录指类所在的根目录。

但在servlet中,相对路径的根目录变成了{tomcat}/bin/目录(因为java虚拟机是在此目录运行)。所以在servlet中便不适合使用相对路径。而适合使用绝对路径。使用方法如下:

 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
		FileInputStream in = new FileInputStream(path);
		Properties prop = new Properties();
		prop.load(in);
		System.out.println(prop.getProperty("oracle-url"));
	}

 

但其实ServletContext还提供了更优雅的方式load .propertes 文件:

 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
		//注意, 虽然此时db.properties 文件是在src文件夹下,但deploy之后,src中的内容都是是放在/WEB-INF/classes/下的。
		Properties prop = new Properties();
		prop.load(in);
		System.out.println(prop.getProperty("oracle-url"));
	}

 

 

当然,如果不在servlet容器中,而在一般的类,如UserDao类中如何load properties 文件呢:

String path = UserDao.class.getClassLoader().getResource("db.properties").getPath();

FileInutStream in = new FileInputStream(path);
Properties prop = new Properties();
prop.load(in);
System.out.println(prop.getProperty("oracle-url"));

 

此方法是使用类加载器按类的方式load 属性文件。缺点: 类加载器对某个类只会加载一次。如果加载过后,手动改了/classes/db.properties 文件,人为地重新执行此function, 类加载器发现它已经加载过这个文件了,便不会重新加载了。

另一种方法:

InputStream in = UserDao.class.getClassLoader().getResourceAsStream("db.properties");
Properties prop = new Properties();
prop.load(in);
System.out.println(prop.getProperty("oracle-url"));

 

此方法能将properties文件load 多次。每次此方法执行, 都会再次load此属性文件。

 

下面这个小例子针对的是系统参数:

 

public class TestProperties {
public static void main(String[] args){
for (Object p : System.getProperties().entrySet()) {
Map.Entry<String,String> entry = (Map.Entry<String, String>)p;
System.out.println(entry.getKey() + "=" + entry.getValue());
}
}
 
public static String getDeploymentEnv()
{
String env = System.getProperty("env");
if(!env.isEmpty())
{
env = System.getenv("env");
}
if(!env.isEmpty())
{
env="";
System.setProperty("env", env);
}
 
return env;
}
 
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值