(一)在web工程中
方法1: 根據系統變量,如獲取tomcat物理路徑
String tomcatHome = System.getenv("TOMCAT_HOME");
String cfg = tomcatHome + File.separator + "webapps"+ File.separator + "bms" + File.separator + "WEB-INF" + File.separator+"bms_config.properties";
2. 根據request對象
String tomcatHome = ServletActionContext.getRequest().getRealPath("/");
tomcatHome = tomcatHome.substring(0, tomcatHome.indexOf("webapps"));
(二)在普通的java工程中(如做批處理的jar)
1、利用System.getProperty()函數獲取當前路徑:
System.out.println(System.getProperty("user.dir"));//user.dir指定了當前的路徑
2、使用File提供的函數獲取當前路徑:
File directory = new File("");//設定為當前文件夾
try{
System.out.println(directory.getCanonicalPath());//獲取標准的路徑
System.out.println(directory.getAbsolutePath());//獲取絕對路徑
}catch(Exceptin e){}