JAVA獲取文件的幾種常用方式
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獲取文件的幾種常用方式