一.软件开发过程中常有的两种配置文件是:
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读取的配置文件不能太大