Java讀取WEB-INF目錄下的properties設定檔__Java

來源:互聯網
上載者:User

    如何在Java代碼中讀取WEB-INF目錄下的properties設定檔,下文給出了一個解決方案。

    我們習慣將一些配置資訊寫在設定檔中,比如將資料庫的配置資訊URL、User和Password寫在設定檔中,這樣部署系統的時候,不需要修改代碼,而只需要修改設定檔即可。

    我將設定檔放在MyEClipse工程檔案夾下的WEB-INF目錄,在Java代碼中讀取設定檔的代碼是這樣的:

String path = ParametersReader.class.getResource("/").getPath();String websiteURL = (path.replace("/build/classes", "").replace("%20"," ").replace("classes/", "") + "parameter.properties").replaceFirst("/", "");
    第一行代碼中的ParametersReader.class指的是當前類的名字,path變數中存放的實際上是當前類所在的路徑。

    這樣的話,我們就得到了當前項目WEB-INF的目錄。我們將資料庫的配置資訊寫在parameter.properties檔案中,這個檔案是放在WEB-INF目錄下的,該設定檔中的內容如下:

#JDBC MySQL Connectionmysql_url=jdbc:mysql://127.0.0.1:3306/mydatabasenamemysql_user=rootmysql_password=123456
    那麼針對上述設定檔,讀取該設定檔的完整代碼應該是這樣的:

public static void getParameters() {String path = ParametersReader.class.getResource("/").getPath();String websiteURL = (path.replace("/build/classes", "").replace("%20"," ").replace("classes/", "") + "parameter.properties").replaceFirst("/", "");Properties properties = new Properties();FileInputStream fileInputStream = null;try {fileInputStream = new FileInputStream(websiteURL);properties.load(fileInputStream);MYSQL_URL = properties.getProperty("mysql_url");MYSQL_USER = properties.getProperty("mysql_user");MYSQL_PASSWORD = properties.getProperty("mysql_password");} catch (Exception e) {e.printStackTrace();} finally {try {fileInputStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
    代碼中的MYSQL_URL,MYSQL_USER,MYSQL_PASSWORD這三個變數都是定義好的靜態變數,getParameters()方法是用來給這三個變數賦值的。
    目前越來越多使用XML檔案代替properties檔案來存放配置資訊,所以,我們也可以將xml檔案放在WEB-INF目錄下,通過dom4j等工具來讀取xml檔案。



----------------------------------------------------2015.12.16更新------------------------------------------------------


用類載入器的方式管理設定檔


方法一:

使用了ClassLoader類載入器,此時需要寫上設定檔的包名路徑,最前面不需要加斜杠。

InputStream is = ReflectTest2.class.getClassLoader().getResourceAsStream("cn/itcast/day1/config.properties");

方法二:

InputStream is = ReflectTest2.class.getResourceAsStream("config.properties");

如果設定檔和ReflectTest2在同一個包下,直接寫設定檔名;

如果設定檔在其他包下,需要寫絕對路徑,路徑最前面還需要帶上斜杠。






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.