Chinaunix首页 | 论坛 | 博客
  • 博客访问: 468056
  • 博文数量: 1496
  • 博客积分: 79800
  • 博客等级: 大将
  • 技术积分: 9940
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-09 13:22
文章分类

全部博文(1496)

文章存档

2011年(1)

2008年(1495)

我的朋友

分类:

2008-09-09 13:30:07


  我们常常使用配置文件来进行工程属性的配置,那么我们如何使用我们的属性文件呢?
  
  假设有一个连接数据库的属性配置文件jdbc.properties,
  
  文件内容如下:
  jdbc.driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
  jdbc.url=jdbc:microsoft:sqlserver://10.0.0.168:1433;
  jdbc.username=sa
  jdbc.password=sa
  jndi.databaseName=northwind
  
  那么如何使用配置文件呢?其实很简单
  
  我们创建如下类:
  /*
  * Created on 2005-8-15
  *This class is created to test the using of  the properties file
  * TODO To change the template for this generated file go to
  * Window - Preferences - - Code Style - Code Templates
  */
  package zy.pro.wd.demo;
  
  
  import java.io.FileInputStream;
  import java.util.Properties;
  
  public class PropertiesDemo {
  
  /**
  *
  */
  public PropertiesDemo() {
  super();
  // TODO Auto-generated constructor stub
  }
  public void testPropertiesFile(){
  try{
  Properties pro = new Properties();
  
  pro.load(new FileInputStream("src/jdbc.properties"));
  System.out.println(pro.getProperty("jdbc.driver"));
  System.out.println(pro.getProperty("jdbc.url"));
  
  }catch(Exception e){
  e.printStackTrace();
  }
  }
  public static void main(String[] args) {
  PropertiesDemo pd=new PropertiesDemo();
  pd.testPropertiesFile();
  }
  }
  
  粗体部分是主要部分,通过load()方法来加载配置文件,然后通过getProperty()方法来取得配置文件中的属性。
  
  注意:取得配置文件的相对路径一定要正确,否则,将会抛出找不到文件的异常。我的配置文件路径如下图:
  
  程序输出结果如下:
  com.microsoft.jdbc.sqlserver.SQLServerDriver
  jdbc:microsoft:sqlserver://10.0.0.168:1433;
  此程序在Eclipse3.0下调试通过。
【责编:admin】

--------------------next---------------------

阅读(84) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~