如何在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在同一個包下,直接寫設定檔名;
如果設定檔在其他包下,需要寫絕對路徑,路徑最前面還需要帶上斜杠。