• J2EE之ServletContext读取资源文件


    ServletContext读取资源文件内容的方式有两种:

    方法1.

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    
    	InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/data.properties");
    	Properties pros = new Properties();
    	pros.load(in);
    		
    	String username = pros.getProperty("username");
    	String password = pros.getProperty("password");
    		
    	System.out.println("username = " + username);
    	System.out.println("password = " + password);
    }


    这里须要注意的是data.properties文件的位置在Myeclipse的src文件夹下,为啥getResourceAsStream方法传入的參数确实"/WEB-INF/classes/data.properties"

    这是由于这些代码有webserver运行,当项目公布以后。data.properties文件就会被放到tomcat安装文件所在目录下。

    如图:


    所以这里传入參数就解释清楚了。

    方法2

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    
    	String path = this.getServletContext().getRealPath("/WEB-INF/classes/data.properties");
    	FileInputStream in = new FileInputStream(path);
    	Properties pros = new Properties();
    	pros.load(in);
    		
    		
    	String username = pros.getProperty("username");
    	String password = pros.getProperty("password");
    		
    	System.out.println("username = " + username);
    	System.out.println("password = " + password);
    }

    这里首先通过getRealPath方法获取data.properties文件的绝对路径,然后通过FileInputStream获取文件流。

  • 相关阅读:
    clickhouse集群部署
    zookeeper集群部署
    linux下安装多路径multipath
    采用xtrabackup部署主从同步(生产)
    部署dg备库同步ogg
    goldengate同步(主库rac从库单节点)
    python3发送邮件
    python2发送邮件
    pip版本过高导致报错
    ERROR 1558 (HY000): Column count of mysql.user is wrong
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5346969.html
Copyright © 2020-2023  润新知