JAVA擷取檔案的幾種常用方式

來源:互聯網
上載者:User

標籤:方式   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擷取檔案的幾種常用方式

聯繫我們

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