2012-07-18 43 views
1

我已經創建了一個dbConnection.properties文件並將其放入WEB-INF。要讀取該文件,並連接到我HAVA寫了一類數據庫閱讀java中使用eclipse連接數據庫的dbConnection.properties文件

public class DbConnection { 

public static Connection connection() 
{ 
    Connection con=null; 
    //String connectionURL = "jdbc:mysql://localhost:3306/demo"; 
    try 
    { 
     Properties prop=new Properties(); 
     FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties")); 
     prop.load(in); 
     in.close(); 

     String drivers = prop.getProperty("jdbc.drivers"); 
     String connectionURL = prop.getProperty("jdbc.url"); 
     String username = prop.getProperty("jdbc.username"); 
     String password = prop.getProperty("jdbc.password"); 

     //Class.forName("com.mysql.jdbc.Driver").newInstance(); 
     Class.forName(drivers); 
     con=DriverManager.getConnection(connectionURL,username,password); 

      System.out.println("Connection Successful"); 
      return con;  
    } 
    catch(Exception e) 
    { 
     System.out.println("error !!"); 
    } 
    return null; 

} 

}

其進入catch塊。我怎樣才能讀取.properties文件?

回答

3

將屬性src下文件,如果你正在使用Eclipse或WEB-INF/classes如果您使用的螞蟻或gradle這個或任何其他工具,爲此事,然後修改聲明

FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties")); 
     prop.load(in); 

prop.load(DbConnection.class.getClassLoader() 
        .getResourceAsStream("dbConnection.properties")); 

進行此更改,它將起作用!

+0

其給出fileNotFoundException – sonam 2012-07-18 07:03:58

+0

你把屬性文件放在src文件夾下嗎?如果您使用ant或其他任何工具如gradle來構建,然後將屬性文件放在WEB-INF/classes下並嘗試 – Patton 2012-07-18 07:09:37

+0

我在src下有兩個包。所以包含DBConnection類的包,我已經把這個文件放到了prjct.db包中。 – sonam 2012-07-18 07:12:16