apache Velocity模版引擎--资源加载方式

1. java加载资源的方式

1.1 通过java i/o提供的接口以普通文件的形式加载

1.2 通过Class 类加载资源

public InputStream getResourceAsStream(String name);

如果使用Class类来加载资源文件需要区分以 '/' 开头和不以 '/'开头。

  • 以 '/'开头:Java以classpath为根目录,直接加上name来搜索资源文件。
  • 不以 '/'开头:资源文件的全路径应该为:调用getResourceAsStream方法的类的package路径加上name。
    /**
     * Add a package name prefix if the name is not absolute Remove leading "/"
     * if name is absolute
     */
    private String resolveName(String name) {
        if (name == null) {
            return name;
        }
        //不以 ‘/’开头处理路径,移除/,包名中.换成/
        /**
         * 比如:com.velocity   -->  com/velocity
        **/
        if (!name.startsWith("/")) {
            Class<?> c = this;
            while (c.isArray()) {
                c = c.getComponentType();
            }
            String baseName = c.getName();
            int index = baseName.lastIndexOf('.');
            if (index != -1) {
                name = baseName.substring(0, index).replace('.', '/')
                    +"/"+name;
            }
        } else {
            //以 / 开头紧紧简单移除 /
            name = name.substring(1);
        }
        return name;
    }

1.3 通过ClassLoader 加载资源

public InputStream getResourceAsStream(String name);

用ClassLoader加载配置文件时,name均不能以"/"开头,在查找时直接在classpath下进行查找。

1.4 java加载资源的demo

1.4.1 项目结构

目录结构

1.4.2 conf.properties

pro=pro

1.4.2 main函数

package com.velocity.resources;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author mingxin
 */
public class ResourcesLoad {

  public static void main(String[] args){
    ResourcesLoad main = new ResourcesLoad();
    try{
      main.loadByClassLoader();
    }catch (IOException e){
      e.printStackTrace();
    }
  }

  public void loadByClass() throws IOException{
    InputStream input = this.getClass().getResourceAsStream("/conf.properties");
    Properties properties = new Properties();
    properties.load(input);
    System.out.println(properties);
  }

  public void loadByClassLoader() throws IOException{
    InputStream input = this.getClass().getClassLoader().getResourceAsStream("conf.properties");
    Properties properties = new Properties();
    properties.load(input);
    System.out.println(properties);
  }
}

2. velocity加载配置文件的方式

2.1 Velocity.init( String propsFilename )

找到 Velocity.init源码

    /**
     *  initialize the Velocity runtime engine, using default properties
     *  plus the properties in the properties file passed in as the arg
     *
     *  @param propsFilename file containing properties to use to initialize
     *         the Velocity runtime
     */
    public static void init( String propsFilename )
    {
        RuntimeSingleton.init(propsFilename);
    }

一路找下去最终可以到ExtendedProperties,可以看到文件的加载是使用new File()来的,这样我们必须给的是绝对路径,所以init一般使用不带参数版本或者Properties作为参数的。

    /**
     * Creates and loads the extended properties from the specified file.
     *
     * @param file  the filename to load
     * @param defaultFile  a second filename to load default values from
     * @throws IOException if a file error occurs
     */
    public ExtendedProperties(String file, String defaultFile) throws IOException {
        this.file = file;

        basePath = new File(file).getAbsolutePath();
        basePath = basePath.substring(0, basePath.lastIndexOf(fileSeparator) + 1);

        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            this.load(in);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {}
        }

        if (defaultFile != null) {
            defaults = new ExtendedProperties(defaultFile);
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,773评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,132评论 18 399
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 11,844评论 0 17
  • 当夜晚要来临的时候,一天繁忙和枯燥的工作依已然结束,坐在值班室中,静静的思考种种得失,毕业工作已经3年了,我一...
    艺术的熏陶1979阅读 1,852评论 0 0
  • 飘雪的冬季, 洁白的大地像底片, 阳光给树梢剪影, 却留下一地的碎金。
    嘉龙阅读 1,430评论 0 2