关于读取Src下配置文件问题解决办法

来源:互联网 发布:培训班java教哪些课程 编辑:程序博客网 时间:2024/06/06 01:19

第一种:

类加载方式
try {
     Properties p = new Properties();
     // 配置文件在class下,即Src下
     p.load(TS.class.getClassLoader().getResourceAsStream("config.properties"));
     String p1 = p.getProperty("name");
     System.out.println("-------" + p1);
} catch (Exception e) {
     e.printStackTrace();
}

第二种
配置文件可以在任何包下面

try {
     // 可以加包名,例如com.config指的是com包下config.properties这个配置文件
     ResourceBundle resbun = ResourceBundle.getBundle("config");
     String p1 = resbun.getString("name");
     System.out.println("-------" + p1);
} catch (Exception e) {
     e.printStackTrace();
}

第三种:
Web工程中我们都可以获得系统的request对象

String realpath = request.getSession().getServletContext().getRealPath("");
try {
     Properties p = new Properties();
     // 获得文件系统分隔符
     String spa = System.getProperty("file.separator");
     // 通过绝对路径获得文件然后获得流
     File file = new File(realpath + spa + "WEB-INF" + spa +"classes" + spa + "config.properties");
     FileInputStream fis = new FileInputStream(file);
     p.load(fis);
     String p1 = p.getProperty("name");
     System.out.println("------" + p1);
} catch (Exception e) {
     e.printStackTrace();
}

第四种:
     属性方式,首先得到环境信息,然后通过系统自己加载某个配置文件。

try {
     Properties p = new Properties();
     ServletContext ctx = request.getSession().getServletContext();
     // 通过环境变量获得配置文件流
     p.load(ctx.getResourceAsStream("WEB-INF/classes/config.properties"));
     String p1 = p.getProperty("name");
     System.out.println("------" + p1);
} catch (Exception e) {
     e.printStackTrace();
}         
}
原创粉丝点击