首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 其他相关 >

关于读取Src上配置文件有关问题解决方法

2013-02-24 
关于读取Src下配置文件问题解决办法第一种:类加载方式try {Properties p new Properties()// 配置文件

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

第一种:

类加载方式
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();
}         
}

热点排行