Web應用讀資源文件


1.資源文件放在src下面,編譯之後就放在web-inf/classes的目錄下了,利用context讀取:

public String test1() {

InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/pro.properties");

         Properties pro = new Properties();

         try {

             pro.load(is);

             String name = pro.getProperty("name");

             return name;

         } catch (IOException e) {

             e.printStackTrace();

             throw new RuntimeException();

         }

 

    }

    public String test2() {

         try {

//獲取文件路徑

Stringpath = this.getServletContext().getRealPath("WEB-INF/classes/pro.properties");

             //獲取文件名

String filename = path.substring(path.lastIndexOf("\\"),path.length());       

             InputStream is = new FileInputStream(path);

             Properties pro = new Properties();

             pro.load(is);

             String name = pro.getProperty("name");

             return name+"-$-----"+filename;

         } catch (IOException e) {

             e.printStackTrace();

             throw new RuntimeException();

         }

}

2. 資源文件放在src下面,普通java類讀取文件

static {

         Properties pro = new Properties();

         InputStream fin = null;

一、直接放在src下面這樣讀

fin= UtilsDb.class.getClassLoader().getResourceAsStream("dbinfo.properties");

二、和當前類放在同一包下,下面這樣讀

fin= UtilsDb.class.getResourceAsStream("dbinfo.properties");

 

         try {

             pro.load(fin);

             driver = pro.getProperty("driver");

             url = pro.getProperty("url");

             name = pro.getProperty("name");

             password = pro.getProperty("password");

             Class.forName(driver);

         } catch (Exception e) {

             e.printStackTrace();

         }

    }

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