日期:2014-05-20  浏览次数:20761 次

读取配置文件内容
java中,如何从配置文件中读取配置内容,比如数据库地址等

------解决方案--------------------
需要看配置文件是什么样的了,如果是properties这种格式的,可以通过Properties这个对象来获取,方式如下:
Java code

        Properties p = new Properties();
        FileInputStream is = new FileInputStream(new File("路径"));
        p.load(is);
        
        // 读取数据库配置
        dbConn.setDriver(p.getProperty("db.driver"));
        dbConn.setUrl(p.getProperty("db.url"));
        dbConn.setUserName(p.getProperty("db.username"));
        dbConn.setPassword(p.getProperty("db.password"));

//配置文件:
db.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
db.url=jdbc:sqlserver://10.148.20.148:1433;databaseName=CI_V3R3_C01
db.username=sa
db.password=wimaxci

------解决方案--------------------
Java code
db.properties文件内容:

username= root 
password = 
url = jdbc:mysql://localhost:3306/study
driver =com.mysql.jdbc.Driver

 

代码:

package org.caijava.example.io ;

import java.io.FileInputStream ;
import java.util.Properties ;
import java.io.IOException ;
import java.sql.Connection ;
import java.sql.DriverManager ;public class ReadProperties{
 

 public static void main(String []args){
   try{
     FileInputStream fis = new FileInputStream("db.properties") ;
     //InputStream is = getClass().getResourceAsStream("db.properties");
      Properties properties = new Properties() ;
 
   properties.load(fis) ;
   String uname = properties.getProperty("username").trim() ;
   String psw = properties.getProperty("password").trim() ;
   String url = properties.getProperty("url").trim() ;
   String driver = properties.getProperty("driver").trim() ;
   System.out.println("driver : "+driver +"\nname :"+ uname+" \npassword :"+psw+"\nurl:"+url) ;
   
   Class.forName(driver) ;
   Connection conn = DriverManager.getConnection(url,uname,psw) ;
  }catch(Exception e){
   e.printStackTrace() ;
  }
 
 }
}