读取配置文件的各种方式
1.类加载器读取:
只能读取classes或者类路径中的任意资源,但是不适合读取特别大的资源。
①获取类加载器 ClassLoader cl = 类名.class.getClassLoader();
②调用类加载器对象的方法:public URL getResource(String name);
此方法查找具有给定名称的资源,资源的搜索路径是虚拟机的内置类加载器的路径。
类 URL 代表一个统一资源定位符,它是指向互联网”资源”的指针。
资源可以是简单的文件或目录,也可以是对更为复杂的对象的引用.
URL对象方法:public String getPath(),获取此 URL 的路径部分。
示例代码:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ClassLoader cl = ServletContextDemo.class.getClassLoader();//得到类加载器
URL url = cl.getResource("cn/edu/c.properties");
String path = url.getPath();
InputStream in = new FileInputStream(path);
Properties props = new Properties();
props.load(in);
System.out.println(props.getProperty("key"));
}
2.类加载器读取:
只能读取classes或者类路径中的任意资源,但是不适合读取特别大的资源。
①获取类加载器 ClassLoader cl = 类名.class.getClassLoader();
②调用类加载器对象的方法:public InputStream getResourceAsStream(String name);
返回读取指定资源的输入流。资源的搜索路径是虚拟机的内置类加载器的路径。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ClassLoader cl = ServletContextDemo.class.getClassLoader();//得到类加载器
InputStream in = cl.getResourceAsStream("cn/edu/c.properties");
Properties props = new Properties();
props.load(in);
System.out.println(props.getProperty("key"));
}
3.ResourceBundle读取:只能读取properties的文件。
ResourceBundle读取的文件是在classpath路径下,也就是src或者src目录下。我们在项目中需要打包,
打包后的properties文件在jar中,修改很不方便,我们需要把properties文件放在jar外随时可以修改。
这样打包后可以直接修改properties文件。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//配置文件名为c.properties在包cn.edu下。
ResourceBundle rb = ResourceBundle.getBundle("cn.edu.c");
System.out.println(rb.getString("key"));
}
4.利用ServletContext可以读取应用中任何位置上的资源。
局限性:只能在web应用中用
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = getServletContext().getRealPath("/WEB-INF/classes/cn/edu/c.properties");
InputStream in = new FileInputStream(path);
Properties props = new Properties();
props.load(in);
System.out.println(props.getProperty("key"));
}