java 擷取當前類的路徑

來源:互聯網
上載者:User

標籤:arp   線程   載入   類載入   apm   設定檔的路徑   current   encoding   pac   

最近在做項目的時候,自己寫了一些配置參數的讀取,將設定檔放到具體的位置,然後讓程式根據當前類的路徑尋找設定檔的路徑,但是,發現eclipse的開發壞境下是可以順利讀取到指定路徑下的設定檔中的配置參數的,

但是當將項目放到Tomcat下  或者 將項目打包成可執行jar包之後,編譯後的class檔案卻讀取不到了開發環境下尋找的設定檔了。

如果在 .java 檔案中直接寫// public static  String Config = "config.properties";  則該路徑指向的就是項目的 src 的同級目錄(直接將設定檔放到項目的根目錄下)

經過尋找資料和進行驗證,現將讀取class檔案相對路徑下設定檔的方法匯總如下:

方法一:使用System擷取路徑

方法二:使用當前類的ProtectionDomain或者ClassLoader擷取路徑

方法三:使用Thread擷取路徑

方法一:

樣本:

 public static  final String URLConfig = System.getProperty("user.dir").replace("bin", "webapps")+"/URLConfig.properties";//這種是將設定檔放到Tomcat的webapps的目錄下

其中的 System.getProperty("user.dir")  為擷取使用者當前工作目錄

java的System.getProperty()方法可以擷取的值

擷取的程式碼範例:

public   class  SystemProperty {      public   static   void  main(String args[]) {         System.out.println("java_vendor:"  + System.getProperty( "java.vendor" ));         System.out.println("java_vendor_url:"                   + System.getProperty("java.vendor.url" ));         System.out.println("java_home:"  + System.getProperty( "java.home" ));         System.out.println("java_class_version:"                   + System.getProperty("java.class.version" ));         System.out.println("java_class_path:"                  + System.getProperty("java.class.path" ));         System.out.println("os_name:"  + System.getProperty( "os.name" ));         System.out.println("os_arch:"  + System.getProperty( "os.arch" ));         System.out.println("os_version:"  + System.getProperty( "os.version" ));         System.out.println("user_name:"  + System.getProperty( "user.name" ));         System.out.println("user_home:"  + System.getProperty( "user.home" ));         System.out.println("user_dir:"  + System.getProperty( "user.dir" ));         System.out.println("java_vm_specification_version:"                  + System.getProperty("java.vm.specification.version" ));         System.out.println("java_vm_specification_vendor:"                  + System.getProperty("java.vm.specification.vendor" ));         System.out.println("java_vm_specification_name:"                  + System.getProperty("java.vm.specification.name" ));         System.out.println("java_vm_version:"                  + System.getProperty("java.vm.version" ));         System.out.println("java_vm_vendor:"                  + System.getProperty("java.vm.vendor" ));         System.out                 .println("java_vm_name:"  + System.getProperty( "java.vm.name" ));         System.out.println("java_ext_dirs:"                  + System.getProperty("java.ext.dirs" ));         System.out.println("file_separator:"                  + System.getProperty("file.separator" ));         System.out.println("path_separator:"                  + System.getProperty("path.separator" ));         System.out.println("line_separator:"                  + System.getProperty("line.separator" ));     }     

 

上面樣本引用的部落格地址:51895823

 

方法二:

樣本1:

public static String getMyDIR(){//擷取當前類檔案的絕對路徑String jarWholePath = ConfigerPraram.class.getProtectionDomain().getCodeSource().getLocation().getFile(); try { //保險起見,將路徑進行decode轉碼jarWholePath = java.net.URLDecoder.decode(jarWholePath, "UTF-8"); } catch (UnsupportedEncodingException e) { System.out.println(e.toString()); } //擷取jar包的上級目錄String jarPath = new File(jarWholePath).getParentFile().getAbsolutePath(); return jarPath;}

樣本2:

/**     * 擷取項目所在路徑     *      * @return     */    public static String getRealPath() {
     //通過類載入器擷取jar包的絕對路徑 String realPath
= MyPath.class.getClassLoader().getResource("") .getFile(); java.io.File file = new java.io.File(realPath); realPath = file.getParentFile().getAbsolutePath(); //擷取jar包的上級目錄
try {
       //路徑decode轉碼 realPath
= java.net.URLDecoder.decode(realPath, "utf-8"); } catch (Exception e) { e.printStackTrace(); }  
    return realPath ; 
  }

 

 

方法三:(該方法還未做驗證,引用部落格:22774537)

Thread.currentThread().getContextClassLoader().getResource("")來得到當前的classpath的絕對路徑的URI標記法

Application可以通過new FileInputStream("xx.properties");直接在classes一級擷取。關鍵是有時我們需要通過web修改設定檔,我們不 能將路徑寫死了。經過測試覺得有以下心得:

1.servlet中讀寫。如果運用Struts 或者Servlet可以直接在初始化參數中配置,調用時根據servlet的getRealPath("/")擷取真實路徑,再根據String file = this.servlet.getInitParameter("abc");擷取相對的WEB-INF的相對路徑。
例:
InputStream input =Thread.currentThread().getContextClassLoader().getResourceAsStream("abc.properties"); 
Properties prop = new Properties();
prop.load(input);
input.close();

prop.setProperty("abc", “test");
prop.store(new FileOutputStream(path), “–test–"); 
out.close(); 

2.直接在jsp中操作,通過jsp內建對象擷取可操作的絕對位址。
例:
// jsp頁面
String path = pageContext.getServletContext().getRealPath("/");
String realPath = path+"/WEB-INF/classes/abc.properties";

//java 程式
InputStream in = getClass().getClassLoader().getResourceAsStream("abc.properties"); // abc.properties放在webroot/WEB-INF/classes/目錄下
prop.load(in);
in.close();

OutputStream out = new FileOutputStream(path); // path為通過頁面傳入的路徑
prop.setProperty("abc", “abcccccc");
prop.store(out, “–test–");
out.close();

3.只通過Java程式操作資源檔
InputStream in = new FileInputStream("abc.properties"); // 相對路徑,項目下的路徑

OutputStream out = new FileOutputStream("abc.properties");

 

下面的參考解釋引用於部落格:https://www.cnblogs.com/gaoxing/p/4703412.html

 

打個簡單的比方,你一個WEB程式,發布到Tomcat裡面運行。
首先是執行Tomcat org.apache.catalina.startup.Bootstrap類,這時候的類載入器是ClassLoader.getSystemClassLoader()。
而我們後面的WEB程式,裡面的jar、resources都是由Tomcat內部來載入的,所以你在代碼中動態載入jar、資源檔的時候,首先應該是使用Thread.currentThread().getContextClassLoader()。如果你使用Test.class.getClassLoader(),可能會導致和當前線程所啟動並執行類載入器不一致(因為Java天生的多線程)。
Test.class.getClassLoader()一般用在getResource,因為你想要擷取某個資源檔的時候,這個資源檔的位置是相對固定的。

java的類載入機制(jvm規範)是委託模型,簡單的說,如果一個類載入器想要載入一個類,首先它會委託給它的parent去載入,如果它的所有parent都沒有成功的載入那麼它才會自己親自來,有點兒像兒子使喚老子的感覺。

 

如果你使用Test.class.getClassLoader(),可能會導致和當前線程所啟動並執行類載入器不一致 :Class.getClassLoader() returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.

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.