java相對路徑怎麼寫
- 綜合知識
- 關注:1.95W次
通用方法: getServletContext().getRealpath("/")+你要訪問的檔案目錄(相對於webRoot的路徑),關鍵是 如何使用getServletContext()方法: 繼承HttpServlet的類下 直接使用getServletContext().getRealpath("/")+相對於webRoot的路徑 即可, struts 1.X下,使用getServlet().getServletContext().getRealPath("/")+相對於webRoot的路徑 struts2 下:首先匯入import org.apache.struts2.ServletActionContext;然後使用其靜態方法 ,使用ServletActionContext.getServletContext().getRealPath("/"),。
2. java web專案 相對路徑怎麼寫servlet裡面通過String basePath=session.getServletContext().getRealPath("/");獲取webRoot目錄真實路百徑。
比如度d:tomcat 6webapps專案名
webRoot下面的resources目錄通過File path = new File(basePath, "resources");獲取
其它同理
如果是內jsp的話,獲取resources目錄直接通容過“<%=request.getContextPath()%>/resources”獲取
3. java怎麼獲取檔案的相對路徑一個例子,如複果有一個Test資料夾裡面有test.java和hello.txt.如果你想用test.java操作制hello.txt只要在test.java中這樣寫2113File file=new File("hello.txt");//這樣就是相對路徑。
如果檔案結構是Test資料夾。 |------test.java。
|------hello.txt。 |------source資料夾。
.. |---------world.txt如果想5261在test.java中操作world.txt。只要這樣寫File file=new File("source/world.txt");另外,在web開發中/代表專案資料夾根目錄,當然也有可能代替webapps,區分方法是:如果/開頭4102的uri是給瀏覽器解析則/代表webapps,如果是給服務1653器後臺解析,則代表專案檔案。
4. java 怎樣獲取一個檔案相對路徑String path = System.getProperty("user.dir")
如果是web裡,方式更多,不過在這裡,這個是最好的。
如果獲得URL或者輸入流,還可以用Class或者ClassLoader的getResource(String name)或者getResourceAsStream(String name)
方法。
private static String path =System.getProperty("user.dir") + File.separator + "com" + File.separator + "sigls" + File.separator + "model" + File.separator + "filter" + File.separator + "tt.txt"; 或者 fileread = new FileReader(new File(Helptxt.class.getResource("/com/sigls/model/filter/tt.txt").toURI() ));
5. java web中讀取檔案,相對路徑怎麼寫相對路徑的話,可以先獲取到當前檔案的編譯路徑,之後在找到想找檔案的路徑的思路來實現。
舉例:
XMLS.class.getClass().getResourceAsStream("/test/test.txt");
解釋:XMLS.class.getClass()是獲取當前的類編譯路徑,之後通過getResourceAsStream的形式即可找到要讀取的檔案的路徑。
備註:這個方法中後面的路徑也可以通過擷取的形式來進行路徑獲取,實現原理都是找到當前類路徑,之後通過相對位置找到另外檔案路徑。
- 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/zonghezhishi/3yml8o.html