方式一:采用ServletContext读取,读取配置文件的realpath,然后通过文件流读取出来。
因为是用ServletContext读取文件路径,可以读取应用任何目录下的任何文件,因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xml和properties。
缺点:不能在servlet外面应用读取配置信息。
方式二:采用ResourceBundle类读取配置信息,
此种方式的优点是:可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非Web应用中读取资源文件。
缺点:只能加载类classes下面的资源文件且只能读取.properties文件。
方式三:采用ClassLoader方式进行读取配置信息,
此种方式的优点是:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息。
因为是用ServletContext读取文件路径,可以读取应用任何目录下的任何文件,因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xml和properties。
缺点:不能在servlet外面应用读取配置信息。
public class ServletContextProperties extends HttpServlet {
// 方式一:利用ServletContext
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取配置文件路径
// String path = getServletContext().getRealPath(
// "/WEB-INF/classes/com/heima/p3.properties");
// String path2 = getServletContext().getRealPath(
// "/WEB-INF/classes/p2.properties");
String path3 = getServletContext()
.getRealPath("/WEB-INF/p1.properties");
Properties properties = new Properties();
// Properties加载关联流文件
properties.load(new FileInputStream(path3));
// 根据建获取值
String property = properties.getProperty("key1");
response.getOutputStream().write(property.getBytes());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
方式二:采用ResourceBundle类读取配置信息,
此种方式的优点是:可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非Web应用中读取资源文件。
缺点:只能加载类classes下面的资源文件且只能读取.properties文件。
public class ResourceBundleProperties extends HttpServlet {
//方式二:利用ResourceBundle
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//注意是基名,无后缀名
ResourceBundle resourceBundle=ResourceBundle.getBundle("com.heima.p3");
//ResourceBundle resourceBundle2=ResourceBundle.getBundle("p2");
response.getOutputStream().write(resourceBundle.getString("key1").getBytes());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
方式三:采用ClassLoader方式进行读取配置信息,
此种方式的优点是:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息。
缺点:只能加载类classes下面的资源文件,不适合读取特别大的文件
public class ClassLoaderPropertiesXml extends HttpServlet {
// 式三:利用类加载器(更加专业)
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ClassLoader classLoader = ClassLoaderPropertiesXml.class
.getClassLoader();
// InputStream stream =
// classLoader.getResourceAsStream("com/heima/p3.properties");
InputStream stream2 = classLoader.getResourceAsStream("p2.properties");
Properties properties = new Properties();
// Properties加载关联流文件
properties.load(stream2);
// 根据建获取值
String property = properties.getProperty("key1");
response.getOutputStream().write(property.getBytes());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
下图仅为参考目录和文件,每个properties的key统一为key1,值是对应的value1,value2,value3