Web应用读资源文件

来源:互联网 发布:living earth mac 编辑:程序博客网 时间:2024/06/06 00:11


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();

         }

    }

原创粉丝点击