Java獲取.class文件路徑

      爲了詳細說明要介紹的幾種方法,本例準備了兩個工程:

Java工程

web工程


  tomcat路徑:D:\tomcat\

、Thread.currentThread().getContextClassLoader().getResource(name).getPath();

        name:資源名稱,例如:"com/test/test.txt"。

(1)name="",  獲取編譯文件.class的路徑根目錄,Java工程的.class文件在本工程的/bin/目錄,web工程在tomcat下的/class/目錄。

String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
System.out.println(path);

Java工程運行結果/D:/workspaceMyeclipse/testProject/bin/

web工程運行結果/D:/tomcat/webapps/webProject/WEB-INF/classes/

(2)name="com/test/",獲取包名的路徑。若包不存在,會拋異常

String path = Thread.currentThread().getContextClassLoader().getResource("com/test/").getPath();
System.out.println(path);

Java工程運行結果/D:/workspaceMyeclipse/testProject/bin/com/test/

web工程運行結果/D:/tomcat/webapps/webProject/WEB-INF/classes/com/test/

(3)name="com/test/test.txt",獲取資源路徑

String path = Thread.currentThread().getContextClassLoader().getResource("com/test/test.txt").getPath();
System.out.println(path);

Java工程運行結果/D:/workspaceMyeclipse/testProject/bin/com/test/test.txt

web工程運行結果/D:/tomcat/webapps/webProject/WEB-INF/classes/com/test/test.txt

Ⅱ、Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();

        Test爲main方法所在類名若在web工程中,可以改寫爲:

this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();

該方法等同於1的(1),能獲取.class文件的根目錄路徑。若要得到.class的路徑,需要自行拼接字符串。例如:

 String path = test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
 String filePath = "com/test/base/java/test1.txt";
 //判斷拼接的路徑是否正確
 File file = new File(path, filePath);
 System.out.println(file.getAbsolutePath());//文件絕對路徑
 System.out.println(file.exists());//文件是否存在
 System.out.println(file.getName());//文件名稱
運行結果
D:\testProject\bin\com\test\test1.txt
true
test1.txt

當要獲取web工程中的html或者js等文件時也可用此法拼接。

Ⅲ、Test.class.getResource(name).getPath();

name:資源名稱,例如:"/com/test/test.txt",與第一種方法類似,區別在於路徑名稱前多一個反斜槓"/"。

(1)name="",獲取Test.class編譯文件所在目錄的絕對路徑,與第一種方法結果不同。

String path = test.class.getResource("").getPath();
System.out.println(path);
運行結果/D:/testProject/bin/com/test/

(2)name="/",獲取.class文件的根目錄路徑,等同於:

 Thread.currentThread().getContextClassLoader().getResource("").getPath();

String path = test.class.getResource("/").getPath();
System.out.println(path);
運行結果/D:/testProject/bin/

(3)name="/com/test/",獲取包名(com.test)的路徑

String path = test.class.getResource("/com/test").getPath();
System.out.println(path);
運行結果/D:/testProject/bin/com/test/

(4)name="/com/test/test.txt",獲取包com.test下名爲test.txt的文件的路徑

String path = test.class.getResource("/com/test/test.txt").getPath();
System.out.println(path);
運行結果/D:/testProject/bin/com/test/test.txt















發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章