java中類路徑下的絕對路徑(通用路徑)


類路徑下的絕對路徑(通用路徑)

  • Class.forName("Myclass");像這種路徑的缺點是:
    移植性差,在IDEA中默認的當前路徑是project的根。如果不是IDEA,換到了其它位置,可能當前路徑就不是project的根了,路徑就會無效。
  • 一種比較通用的路徑
    即使代碼換位置了,這樣編寫仍然是通用的。(適用於任何操作系統)
    注意:使用以下通用方式的前提是:這個文件必須在類路徑下。(放在src下的都是類路徑下,src是類的根路徑。)
  • 代碼示例
public class Demo{
    public static void main(String[] args){

        /*
        Thread.currentThread():當前線程對象。
        getContextClassLoader():是線程對象的方法,
        可以獲取到當前線程的類加載器對象。
        getResource():(獲取資源)這是類加載器對象的方法,
        當前線程的類加載器默認從類的根路徑下加載資源。
        */

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

輸出:
在這里插入圖片描述
這里返回的是class文件所在的目錄。所以不能獲取java文件的路徑,只能把.java改為.class:
getResource("Demo.class")
輸出:
在這里插入圖片描述

以流的形式返回路徑

  • 代碼示例
    在這里插入圖片描述
import java.io.InputStream;
import java.util.Properties;

public class Demo{
    public static void main(String[] args) throws Exception{
        InputStream path = Thread.currentThread()
                .getContextClassLoader()
                .getResourceAsStream("classinfo.properties");
        Properties pro = new Properties();
        pro.load(path);
        path.close();
        String className = pro.getProperty("className");
        System.out.println(className);
    }
}

輸出:
在這里插入圖片描述

資源綁定器

  • 概述
    1、使用資源綁定器便於獲取屬性配置文件中的內容。
    2、只能綁定xxx.properties文件,但是路徑后面的擴展名不能寫。(.properties不能寫)
    3、使用的時候,屬性配置文件必須放到類路徑下。
  • 代碼示例
    在這里插入圖片描述
import java.util.ResourceBundle;

public class Demo{
    public static void main(String[] args) throws Exception{
        ResourceBundle bundle = ResourceBundle.getBundle("classinfo");
        String date = bundle.getString("date");
        System.out.println(date);
    }
}

輸出:
在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM