本文目錄一覽:
java項目路徑文件怎麼寫
有絕對路徑與相對路徑兩種:
絕對路徑 :以引用文件之網頁所在位置為參考基礎,而建立出的目錄路徑。
絕對路徑:以Web站點根目錄為參考基礎的目錄路徑。
java中類加載路徑和項目根路徑獲取有幾種方式?
package my;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class MyUrlDemo {
public static void main(String[] args) {
MyUrlDemo muDemo = new MyUrlDemo();
try {
muDemo.showURL();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void showURL() throws IOException {
// 第一種:獲取類加載的根路徑 D:\git\daotie\daotie\target\classes
File f = new File(this.getClass().getResource(“/”).getPath());
System.out.println(f);
// 獲取當前類的所在工程路徑; 如果不加“/” 獲取當前類的加載目錄 D:\git\daotie\daotie\target\classes\my
File f2 = new File(this.getClass().getResource(“”).getPath());
System.out.println(f2);
// 第二種:獲取項目路徑 D:\git\daotie\daotie
File directory = new File(“”);// 參數為空
String courseFile = directory.getCanonicalPath();
System.out.println(courseFile);
// 第三種: file:/D:/git/daotie/daotie/target/classes/
URL xmlpath = this.getClass().getClassLoader().getResource(“”);
System.out.println(xmlpath);
// 第四種: D:\git\daotie\daotie
System.out.println(System.getProperty(“user.dir”));
/*
* 結果: C:\Documents and Settings\Administrator\workspace\projectName
* 獲取當前工程路徑
*/
// 第五種: 獲取所有的類路徑 包括jar包的路徑
System.out.println(System.getProperty(“java.class.path”));
}
}
通過java獲取當前項目路徑
getClass().getResource() 方法獲得相對路徑( 此方法在jar包中無效。返回的內容最後包含/)
例如 項目在/D:/workspace/MainStream/Test
在javaProject中,getClass().getResource(“/”).getFile().toString() 返回:/D:/workspace/MainStream/Test/bin/
public String getCurrentPath(){
//取得根目錄路徑
String rootPath=getClass().getResource(“/”).getFile().toString();
//當前目錄路徑
String currentPath1=getClass().getResource(“.”).getFile().toString();
String currentPath2=getClass().getResource(“”).getFile().toString();
//當前目錄的上級目錄路徑
String parentPath=getClass().getResource(“../”).getFile().toString();
return rootPath;
}
參考資料:
java 獲取項目本地路徑?
因為你的項目的執行文件文件就在tomcat路徑下呀,你可以把tomcat的項目路徑指定為你項目的路徑,這樣運行文件就是在你的項目下了,獲取的路徑就是你真正項目的路徑了
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/240126.html