zoukankan      html  css  js  c++  java
  • JavaWeb读取资源文件的四种方式

    1. ServletContext

    1. 调用getResourcesAsStream方法获取输入流, 相对于webroot, 不用加/
    2. 读取任何类型的文件
    3. *只能在web环境下使用

    InputStream in = this.getServletContext().getResourceAsStream("WEB-INF/classes/config/db.properties");

    2. 类加载器

    1. 相对于类路径, 可以获取类路径下及其子包路径下的资源文件
    2. 可以用在非web环境下
    3. 读取任何类型的文件

    InputStream in = ReadFileDemo2.class.getResourceAsStream("/config/db.properties");

    3. 流

    1. 通过ServletContext的getRealPath方法获取文件真实路径, 然后操作文件流, 相对于webroot. 不用加/

    String realPath = this.getServletContext().getRealPath("WEB-INF/classes/config/db.properties");

    4. ResourceBundle

    新建4个资源文件

    1 my_en_US.properties:cancelKey=cancel
    2 my_zh_CN.properties:cancelKey=u53D6u6D88(取消)
    3 my_zh.properties:cancelKey=u53D6u6D88zh(取消zh)
    4 my.properties:cancelKey=u53D6u6D88default(取消default)

    使用ResourceBundle读取资源文件

    1 ResourceBundle bundle = ResourceBundle.getBundle("my", new Locale("zh", "CN"));
    2 String cancel = bundle.getString("cancelKey");
    3 System.out.println(cancel);

    1. 可以用在非web环境下
    2. 只能读取类路径中的properties文件

    备注: ServletContext和流两种方法的区别在于获取流的方式不一样

  • 相关阅读:
    docker-machine create ,,,
    docker run with zabbix3.0
    mysql 官网
    取模性质
    欧涛最短路【记录最短路径】
    P4568 飞行路线【分层图最短路】
    CCF201403 无线网络【限制型最短路】
    POJ2449 【第k短路/A*】
    Feeding Time 【bfs求最大连通块】
    printf特殊用法
  • 原文地址:https://www.cnblogs.com/shaohsiung/p/9595264.html
Copyright © 2011-2022 走看看