標籤:方式 path log 讀取 擷取檔案 csdn height color ==
1、user.dir
System.out.println(System.getProperty("user.dir"));
此方擷取的是啟動並執行路
比如
1、
2、如果在eclipse上運行則是eclipse運行檔案同級
3、tomcat則在
4、File file = new File("log4j.properties");
這裡的log4j.properties也是在以上類型的目錄下尋找
5、FileInputStreaminput = newFileInputStream("log4j.properties");
與File一樣,在運行路徑上找檔案
2、擷取絕對路徑
方法 String in = LogUtil.class.getResource("/").getPath();
或者:this.getClass().getClassLoader().getResource("/").getPath()
結果:
/E:/temp/springmvc/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/rentBook/WEB-INF/classes/
LogUtil.class.getResource("/").getPath(); 加個”/”就會列印classes下的絕對路徑
LogUtil.class.getResource("").getPath(); 就會顯示classes + 包名
Tomcat列印如下:
WEB工程
this.getServletContext().getRealPath("/")
返回:
工程的絕對路徑/返回的也稱為“根”
比如工程:
Book
|_WEB-INF
|_xx.properties
返回d:\Book\
3、相對路徑:
InputStream input = LogUtil.class.getResourceAsStream("/log4j.properties");
讀取的是src/log4j.properties 下的檔案
而
InputStream input = LogUtil.class.getResourceAsStream("log4j.properties");
讀取的是 與LogUtil同級的log4j.properties
第二種:
getServletConfig().getServletContext()
.getResourceAsStream("report1.jasper")
訪問的是根路徑
Book
|_WEB-INF
|_xx.properties
|_report1.jasper
JAVA擷取檔案的幾種常用方式