1 package cn.itcast; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 //servlet调用其他程序,在其他程序中何如读取资源文件(通过类装载器) 12 public class ServletDemo3 extends HttpServlet { 13 14 15 public void doGet(HttpServletRequest request, HttpServletResponse response) 16 throws ServletException, IOException { 17 18 UserDao dao = new UserDao(); 19 dao.find(); 20 21 } 22 23 24 public void doPost(HttpServletRequest request, HttpServletResponse response) 25 throws ServletException, IOException { 26 27 28 } 29 30 }
1 package cn.itcast; 2 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.util.Properties; 8 9 //如果读取资源文件的程序不是servlet的话,就只能通过类装载器去读 10 public class UserDao { 11 12 private static Properties dbconfig = new Properties(); 13 static { 14 InputStream in = UserDao.class.getClassLoader().getResourceAsStream( 15 "db.properties"); 16 try { 17 dbconfig.load(in); 18 } catch (IOException e) { 19 throw new ExceptionInInitializerError(e); 20 } 21 } 22 //以下代码虽然可以读取资源文件数据,但是无法获取更新后的数据 23 public void update() throws IOException { 24 25 System.out.println(dbconfig.getProperty("url")); 26 } 27 28 //通过类装载的方式得到资源文件位置,再通过传统方式读取资源文件的数据,这样可以读取更新后的数据 29 public void find() throws IOException { 30 String path = UserDao.class.getClassLoader().getResource("db.properties").getPath(); 31 FileInputStream in = new FileInputStream(path); 32 33 Properties dbconfig = new Properties(); 34 dbconfig.load(in); 35 36 System.out.println(dbconfig.getProperty("url")); 37 38 } 39 40 }
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.4" 3 xmlns="http://java.sun.com/xml/ns/j2ee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 6 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 7 8 <servlet> 9 <servlet-name>ServletDemo1</servlet-name> 10 <servlet-class>cn.itcast.ServletDemo1</servlet-class> 11 </servlet> 12 <servlet> 13 <servlet-name>ServletDemo3</servlet-name> 14 <servlet-class>cn.itcast.ServletDemo3</servlet-class> 15 </servlet> 16 17 18 19 <servlet-mapping> 20 <servlet-name>ServletDemo1</servlet-name> 21 <url-pattern>/ServletDemo1</url-pattern> 22 </servlet-mapping> 23 <servlet-mapping> 24 <servlet-name>ServletDemo3</servlet-name> 25 <url-pattern>/servlet/ServletDemo3</url-pattern> 26 </servlet-mapping> 27 28 <welcome-file-list> 29 <welcome-file>index.jsp</welcome-file> 30 </welcome-file-list> 31 </web-app>
WEB应用中的普通Java程序如何读取资源文件,布布扣,bubuko.com
原文:http://www.cnblogs.com/aineko/p/3817272.html