3个不同位置的配置文件:a.properties位于WebRoot的根目录,b.properties位于src的下,c.properties位于src中的com.neu包中。其中a.properties中的内容是hello=helloa,b.properties中的内容是hello=hellob,c.properties中的内容是hello=helloc;
如图所示:
ServletContextDemo5.java文件中的程序:
运行:
运行:http://localhost:8080/ServletDemo/servlet/ServletContextDemo5package com.neu; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Properties; import java.util.ResourceBundle; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //读取配置文件的3中方式 public class ServletContextDemo5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // test31(request,response); // test30(request,response); // test20(request,response); test10(request,response); } //请不要把Tomcat等服务器装在有空格的目录中 //类加载器读取:只能读取classes或者类路径中的任意资源。但不适合读取特别大的资源。 b c private void test31(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ ClassLoader cl = ServletContextDemo5.class.getClassLoader();//得到类加载器 URL url = cl.getResource("com/neu/c.properties"); String path = url.getPath(); InputStream in = new FileInputStream(path); Properties props = new Properties(); props.load(in); System.out.println(props.getProperty("hello")); } //类加载器读取:只能读取classes或者类路径中的任意资源。但不适合读取特别大的资源。b c private void test30(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ ClassLoader cl = ServletContextDemo5.class.getClassLoader();//得到类加载器 // InputStream in = cl.getResourceAsStream("b.properties"); InputStream in = cl.getResourceAsStream("com/neu/c.properties"); Properties props = new Properties(); props.load(in); System.out.println(props.getProperty("hello")); } //利用ResourceBundle读取:b c,不能读a,只能读取properties文件 private void test20(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ // ResourceBundle rb = ResourceBundle.getBundle("b"); ResourceBundle rb = ResourceBundle.getBundle("com.neu.c"); System.out.println(rb.getString("hello")); } //利用ServletContext读取:a b c //可以读取应用中任何位置上的资源。使用限制:只能在web应用中用 private void test10(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ // String path = getServletContext().getRealPath("/a.properties"); // String path = getServletContext().getRealPath("//WEB-INF/classes/b.properties"); String path = getServletContext().getRealPath("/WEB-INF/classes/com/neu/c.properties"); InputStream in = new FileInputStream(path); Properties props = new Properties(); props.load(in); System.out.println(props.getProperty("hello")); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
结果:服务器的控制台输出:helloc