只能讀取classes或者類路徑中的任意資源,但是不適合讀取特別大的資源。 ①獲取類加載器 ClassLoader cl = 類名.class.getClassLoader(); ②調用類加載器對象的方法:public URL getResource(String name); 此方法查找具有給定名稱的資源,資源的搜索路徑是虛擬機的內置類加載器的路徑。 類 URL 代表一個統一資源定位符,它是指向互聯網”資源”的指針。 資源可以是簡單的文件或目錄,也可以是對更為復雜的對象的引用. URL對象方法:public String getPath(),獲取此 URL 的路徑部分。 示例代碼:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ClassLoader cl = ServletContextDemo.class.getClassLoader();//得到類加載器 URL url = cl.getResource("cn/edu/c.2.類加載器讀?。?/h2>只能讀取classes或者類路徑中的任意資源,但是不適合讀取特別大的資源。 ①獲取類加載器 ClassLoader cl = 類名.class.getClassLoader(); ②調用類加載器對象的方法:public InputStream getResourceAsStream(String name); 返回讀取指定資源的輸入流。資源的搜索路徑是虛擬機的內置類加載器的路徑。
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ClassLoader cl = ServletContextDemo.class.getClassLoader();//得到類加載器 InputStream in = cl.getResourceAsStream("cn/edu/c.properties"); Properties props = new Properties(); props.load(in); System.out.println(props.getProperty("key")); }ResourceBundle讀取的文件是在classpath路徑下,也就是src或者src目錄下。我們在項目中需要打包, 打包后的properties文件在jar中,修改很不方便,我們需要把properties文件放在jar外隨時可以修改。 這樣打包后可以直接修改properties文件。
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //配置文件名為c.properties在包cn.edu下。 ResourceBundle rb = ResourceBundle.getBundle("cn.edu.c"); System.out.println(rb.getString("key")); }局限性:只能在web應用中用
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = getServletContext().getRealPath("/WEB-INF/classes/cn/edu/c.properties"); InputStream in = new FileInputStream(path); Properties props = new Properties(); props.load(in); System.out.println(props.getProperty("key")); }新聞熱點
疑難解答