• Servlet读取配置文件的三种方式


    一、利用ServletContext.getRealPath()[或getResourceAsStream()]

    特点:读取应用中的任何文件。只能在web环境下。

    1 private void text3(HttpServletResponse response) throws IOException, IOException{
    2         InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db/config/db3.properties");
    3         Properties prop = new Properties();
    4         prop.load(in);
    5         String value = prop.getProperty("db3");
    6         response.getWriter().print(value);
    7 }

    二、利用ResourceBundle读取配置文件

    特点:可以用在非web环境下。但是只能读取类路径中的properties文件

    1 private void text2(HttpServletResponse response) throws IOException{
    2         ResourceBundle rd = ResourceBundle.getBundle("db.config.db3");
    3         String value = rd.getString("db3");
    4         response.getWriter().print(value);
    5 }

    三、利用类加载器读取配置文件(专业)

    特点:可以用在非web环境下。可以读取类路径下的任何文件

    1 private void text1(HttpServletResponse response) throws IOException{
    2         ClassLoader cl = ServletDemo1.class.getClassLoader();
    3         InputStream in = cl.getResourceAsStream("com/ztq/servlet/db4.properties");
    4         Properties prop = new Properties();
    5         prop.load(in);
    6         String value = prop.getProperty("db4");
    7         response.getWriter().print(value);
    8 }
  • 相关阅读:
    python获取当前路径
    python的StringIO
    python判断两个文件是否相同
    Linux查找文件内容
    python日志syslog运用
    python获取当前运行程序的名字
    python连接Linux命令行
    python预编译函数compile,exec,eval
    python日志模块
    Scala安装教程
  • 原文地址:https://www.cnblogs.com/zhangtianq/p/6383291.html
Copyright © 2020-2023  润新知