读取web中的资源配置文件
来源:互联网 发布:bat批处理卸载软件 编辑:程序博客网 时间:2024/05/01 07:36
一.软件开发过程中常有的两种配置文件是:
1. .xml配置文件
2. .properties配置文件
当要用的数据间没有关系是用到.properties文件。
二.在servlet中一般使用ServletContext读取.properites配置文件。一般代码格式为:
InputStream in=this.getServletContext().getResourceAsStream("对应web映射到服务器下得目录");
Properties prop=new Properties();
rops.load(in);
props.getProperty("");//对应properties文件中等号(“=”)左面的数据
三.如配置文件为:
url=jdbc:mysql://localhost:3306/test
username=root
password=root
读取方式:
InputStream in=this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");//目录为服务器下对应的目录,在本地磁盘映射到服务器下得目录, 此 处是在本地src目录下若再cn.itcast包下则为/WEB-INF/classes/cn/itcast/db.properties,若在webroot下则直接为/db.properties
Properties props=new Properties();//map
props.load(in);
String url=props.getProperty("url");
String username=props.getProperty("username");
String password=props.getProperty("password");
注:
读取资源文件需要注意的问题:下面代码不可行,最好采用servletContext去读
private void test4() throws IOException {
FileInputStream in =new FileInputStream("src/db.properties");//改成classes目录也不行,采用相对路径,相对类加载器的目录(服务器启动目录)
Properties props=new Properties();
props.load(in);
可以通过servletContext的getRealPath得到资源的绝对路径后,再通过传统流读取资源文件,可以得到文件的名称
private void test5() throws IOException {
String path=this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
FileInputStream in=new FileInputStream(path);
Properties props=new Properties();
props.load(in);
四.得到配置文件的文件名
String path=this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");//得到真实路径名
String filename=path.substring(path.lastIndexOf("\\")+1);//注意加1
System.out.println("当前读取到得资源名称是:"+filename);
FileInputStream in=new FileInputStream(path);
Properties props=new Properties();
props.load(in);
五.不是servlet的java程序读取web配置文件
虽然可以使用参数传递ServletContext,但不使用,外部侵入了数据库层,不符合软件设计思想。只能通过类装载器去读了,类装载器不仅可以装载类,也可以装载配置文件。
Properties dbconfig=new Properties();
InputStream in=UserDao.class.getClassLoader().getResourceAsStream("db.properties");
dbconfig.load(in);
虽然可以读取资源文件的数据,但是无法获取更新后的数据。通过类装载器的方式得到资源文件的位置,再通过传统方式读取资源文件的数据,这样可以读取到更新后的数据:
String path=UserDao.class.getClassLoader().getResource("db.properties").getPath();
FileInputStream in=new FileInputStream(path);
Properties dbconfig=new Properties();
dbconfig.load(in);
注意:servletcontext读取的配置文件不能太大
- 读取web中的资源配置文件
- 读取web中的资源配置文件
- servlet读取资源配置文件
- ServletContext读取资源配置文件
- java中的资源配置文件
- Spring Resource 读取资源配置文件
- 简单的JDBC数据库连接池、读取资源配置文件
- ServletContext读取web应用中的资源文件
- ServletContext 读取Web应用中的资源文件
- javaweb读取 web 应用中的资源文件
- jar读取资源配置文件,jar包内包外,以及包内读取目录的方法
- log4j.properties资源配置文件
- Struts2 资源配置文件国际化
- Struts2 资源配置文件国际化
- Unity3D自定义资源配置文件
- 使用ResourceBundle 读取资源配置信息
- spring boot框架学习之重要注解3注解方式读取外部资源配置文件
- java_web11-ServletContext读取Web应用中的资源文件
- 1314
- 参数传递二维数组
- java 技术提升,复习,总结(二)
- PHP开发框架流行度排名:Laravel居首
- java代码中 两种路径符号的写法
- 读取web中的资源配置文件
- android版本更新全程解析
- 如何让DIV相对于body水平和垂直居中
- 明天你好
- 融合架构
- Linux下tomcat的安装启动及停止
- 算法之排序-----排序第三篇 选择排序
- 不敢惹相思
- 链表的插入操作