java讀取資源檔的N種方法

來源:互聯網
上載者:User
如何讀取資源檔:(一)Properties props = new Properties();   props.load(new FileInputStream("db.properties"));(二)blog.properties檔案如下dbdriver=oracle.jdbc.driver.OracleDriverdburl=jdbc:oracle:thin:@127.0.0.1:1521:ora92dbuser=blogdbpwd=blog--------------public class Config {public Config() {    this.initDBConfig();}public String DBdriver;public String DBuser;public String DBpwd;public String DBurl;private void initDBConfig() {    try {      ResourceBundle bundle = ResourceBundle.getBundle("blog");      DBdriver = bundle.getString("dbdriver");      DBurl = bundle.getString("dburl");      DBuser = bundle.getString("dbuser");      DBpwd = bundle.getString("dbpwd");    }    catch (Exception ex) {      ex.printStackTrace();    }}}----------------public class DAO {public DAO() {}public Connection getConnection() {    Connection conn = null;    Config config = new Config();    String DBdriver = config.DBdriver;    String DBuser = config.DBuser;    String DBpwd = config.DBpwd;    String DBurl = config.DBurl;    try {      Class.forName(DBdriver);      conn = DriverManager.getConnection(DBurl, DBuser, DBpwd);    }    catch (Exception ex) {      System.out.println("********************");      System.out.println("不能得到資料庫連接");      System.out.println("DBdriver: " + DBdriver);      System.out.println("DBuser: " + DBuser);      System.out.println("DBpwd: " + DBpwd);      System.out.println("DBurl: " + DBurl);      ex.printStackTrace();    }    return conn;}}(三)Properties props=new Properties();props.load(BugFactory. class.getResourceAsStream("xx.properties"));String name = props.getPropery("xxxx");此時xx.properties應該與該類放在同一個目錄.(四)ResourceBundle res = ResourceBundle.getBundle("yy.properties");String name = res.getString("yyyy");yy.properties應放在/WEB-INF/classes目錄(五)如果你這個Bean打包的話,就把這個檔案放在包內。我一般是這樣寫的Properties prop = new Properties();try{InputStream is = getClass().getResourceAsStream("db.properties");prop.load(is);if(is!=null)    is.close();}另:props.load(new FileInputStream("db.properties")); 是讀取目前的目錄的db.properties檔案getClass.getResourceAsStream("db.properties"); 是讀取當前類所在位置一起的db.properties檔案getClass.getResourceAsStream("/db.properties"); 是讀取ClassPath的根的db.properties檔案,注意ClassPath如果是多個路徑或者jar檔案的,只要在任意一個路徑目錄下或者 jar檔案裡的根下都可以,如果存在於多個路徑下的話,按照ClassPath中的先後順序,使用先找到的,其餘忽略

轉自 : http://blog.csdn.net/kjfcpua/article/details/4888899

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.