【JavaEE】读取配置文件路径的几种方式

读取配置文件的各种方式

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"));
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值