处理配置文件对于Java程序员来说再常见不过了,不管是Servlet,Spring,抑或是Structs,都需要与配置文件打交道。Java将配置文件当作一种资源(resource)来处理,并且提供了两个类来读取这些资源,一个是Class类,另一个是ClassLoader类。

  当我们自己的程序需要处理配置文件时(比如xml文件或properties文件),通常会遇到两个问题:

  (1)我的配置文件应该放在哪里?

  (2)怎么我的配置文件找不到了?

  在了解了Java加载资源文件的机制后,以上这两个问题便迎刃而解了。

  对于第一个问题,答案是:请将你的资源文件放在classpath里,如果资源文件在jar中,请将该jar文件也加到classpath里面。

  对于第二个问题,就得看你是使用的是哪个类(Class还是ClassLoader)来加载资源文件了,所以接下来分别讨论一下Class类和ClassLoader类对于资源文件的加载机制。

  (一)用Class类加载资源文件

  通过调用Class类的getResourceAsStream方法来加载资源文件:

  public InputStream getResourceAsStream(String pathToConfigFile);

  该方法接收一个String类型的参数(pathToConfigFile)来表示资源文件的地址,如果加载成功,则返回该资源文件的输入流(InputStream),如果失败,则返回null。重要的是,在传入pathToConfigFile参数时,有两种方式,第一种方式为绝对定位方式,即pathToConfigFile以"/"开头,此时Java以classpath为根目录,直接加上pathToConfigFile来搜索资源文件。第二种方式为相对定位方式,即pathToConfigFile不以"/"开头,此时资源文件的全路径应该为:调用getResourceAsStream方法的类的package路径加上pathToConfigFile。(在将package转为目录时将"."变成"/")

  举个例子,在IntelliJ Idea中创建一个java工程,目录结构如下:

  该工程里有两个resources文件夹,一个位于davenkin文件夹下,一个直接位于src文件夹下。第一个resources文件夹下有一个config.properties文件,其内容为:

name = ConfigUnderDavenkin

  第二个resources文件夹下也有一个config.properties文件,其内容为:

name = ConfigUnderSrc

在davenkin包下定义ResourceLoader.java来加载资源文件:

package davenkin;

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

public class ResourceLoader
{
    public static void main(String[] args) throws IOException
    {
        ResourceLoader resourceLoader = new ResourceLoader();
        resourceLoader.loadProperties1();

}

public void loadProperties1() throws IOException
    {
        InputStream input = null;
        try
        {
            input = Class.forName("davenkin.ResourceLoader").getResourceAsStream("/resources/config.properties");

//also can be this way:
            //input = this.getClass().getResourceAsStream("/resources/config.properties");
        } catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        printProperties(input);
    }

private void printProperties(InputStream input) throws IOException
    {
        Properties properties = new Properties();
        properties.load(input);
        System.out.println(properties.getProperty("name"));
    }
}

  输出结果为第二个resources文件夹下config.properties的内容:

ConfigUnderSrc

  原因在于(请注意ReourceLoader.java文件中的红色部分):我们给出的资源文件路径(/resources/config.properties)以"/"开头,即使用的是绝对定位方式,所以找到的是直接在classpath下的resources文件夹。如果去掉资源文件文件路径前的"/",则采用的是相对定位方式,此时应该输出davenkin/resources/config.properties文件的内容。

  (二)用ClassLoader类加载资源文件

  ClassLoader类也提供和Class类相同的加载方法:

  public InputStream getResourceAsStream(String pathToConfigFile);

  用ClassLoader加载配置文件时,pathToConfigFile均不能以"/"开头,在查找时直接在classpath下进行查找。Class类在查找资源文件时,也是代理(delegate)给ClassLoader完成查找功能的,请参考Java官方文档。

在使用Class和ClassLoader加载资源文件时,有几种区别细微的方法,修改ResourceLoader.java文件如下:

package davenkin;

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

public class ResourceLoader
{
    public static void main(String[] args) throws IOException
    {
        ResourceLoader resourceLoader = new ResourceLoader();
        resourceLoader.loadProperties1();
        resourceLoader.loadProperties2();
        resourceLoader.loadProperties3();
        resourceLoader.loadProperties4();
        resourceLoader.loadProperties5();
        resourceLoader.loadProperties6();
    }

public void loadProperties1() throws IOException
    {
        InputStream input = null;
        try
        {
            input = Class.forName("davenkin.ResourceLoader").getResourceAsStream("/resources/config.properties");
        } catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        printProperties(input);
    }

public void loadProperties2() throws IOException
    {
        InputStream input = null;

input = this.getClass().getResourceAsStream("/resources/config.properties");
        printProperties(input);
    }

public void loadProperties3() throws IOException
    {
        InputStream input = this.getClass().getResourceAsStream("resources/config.properties");
        printProperties(input);
    }

public void loadProperties4() throws IOException
    {
        InputStream input = this.getClass().getClassLoader().getResourceAsStream("resources/config.properties");
        printProperties(input);
    }

public void loadProperties5() throws IOException
    {
        InputStream input = ClassLoader.getSystemResourceAsStream("resources/config.properties");
        printProperties(input);
    }

public void loadProperties6() throws IOException
    {
        InputStream input = ClassLoader.getSystemClassLoader().getResourceAsStream("resources/config.properties");

printProperties(input);
    }

private void printProperties(InputStream input) throws IOException
    {
        Properties properties = new Properties();
        properties.load(input);
        System.out.println(properties.getProperty("name"));
    }
}

  以上程序输出结果为(请仔细揣摩,稍不小心(比如多加了一个"/"或少加了一个"/"),就会报NullPointerException异常,表明你的资源文件没有找到):

ConfigUnderSrc
ConfigUnderSrc
ConfigUnderDavenkin
ConfigUnderSrc
ConfigUnderSrc
ConfigUnderSrc

Java加载资源文件的两种方法的更多相关文章

  1. xml文件 加载properties文件的两种方法与注意事项

    1.遇到的问题: 配置redisSpringContext.xml 时,遇到 properties加载失败,提示BeanDefinitionStoreException  和   java.lang. ...

  2. 动态加载script文件的两种方法

    第一种就是利用ajax方式,把script文件代码从后台加载到前台,然后对加载到的内容通过eval()执行代码.第二种是,动态创建一个script标签,设置其src属性,通过把script标签插入到页 ...

  3. 加载xib文件的两种方式

    一.加载xib文件的两种方式 1.方法一(NewsCell是xib文件的名称) NSArray *objects = [[NSBundle mainBundle] loadNibNamed:@&quo ...

  4. Spring加载properties文件的两种方式

    在项目中如果有些参数经常需要修改,或者后期可能需要修改,那我们最好把这些参数放到properties文件中,源代码中读取properties里面的配置,这样后期只需要改动properties文件即可, ...

  5. Java加载资源文件几种方法

    from: http://andyzhu.blog.51cto.com/4386758/775836/ import java.net.URL; import org.springframework. ...

  6. windows/tomcat 修改java虚拟机JVM以utf-8字符集加载class文件的两种方式

      1.情景展示 做了这么长时间的java开发,但是,你知道JVM是以怎样的编码加载.解析class文件的吗? 我们知道,通常情况下,我们会将java文件的字符集修改成utf-8,这样,理所当然地就认 ...

  7. java加载资源文件

    className.class.getResourceAsStream 用法: 第一: 要加载的文件和.class文件在同一目录下,例如:com.x.y 下有类Test.class ,同时有资源文件c ...

  8. [ARM-Linux开发]Linux下加载.ko驱动模块的两种方法:insmod与modprobe

    假设要加载的驱动程序模块名为SHT21.ko 加载驱动模块 方法一:  进入SHT21.ko驱动模块文件所在的目录,然后直接  insmod SHT21.ko  即可 方法二:  将SHT21.ko文 ...

  9. 加载properties文件的三种方法

    源代码: package a.one; import java.io.FileInputStream; import java.io.InputStream; import java.util.Pro ...

随机推荐

  1. 【分享】jQuery无插件实现 鼠标拖动图片切换 功能

    前言 我就想随便叨逼叨几句,爱看就看几句,不爱看就直接跳过看正文就好啦~ 这个方法是仿写页面时我自己研究出来,可能有比我更简单的方法. 但我不管,因为我没查我不知道,我就觉得我的最好啦,耶耶耶~ 效果 ...

  2. Python之hashlib模块

    hashlib 在做一个授权管理系统,需要生产动态生成密码,故使用hashlib >>> import time >>> import hashlib >&g ...

  3. linux服务器上Apache配置多域名

    一, 打开httpd.conf 二 找到如下三个位置配置如下 DocumentRoot "/data" #以下这个配置是紧挨着的,有两个 <Directory "/ ...

  4. AES加密实现

    起因 这段时间因为要对接一个外部接口,其参数的加密方式为AES,就需要学下AES的加密写法,但网上的资料不是很全,自己记录下遇到的坑: 基本写法 String str = "hello&qu ...

  5. python常用数据结构

    0. 字典初始化 d = {'a':1,'b':2} 或 d={} d['a'] = 1 d['b'] = 2 是不是和json格式数据很相似,语法和JavaScript又很相似 1. 变量接受序列分 ...

  6. Cocos2D-X屏幕适配新解

    ”   阅读器 为了适应移动终端的各种分辨率大小,各种屏幕宽高比,在 Cocos2D-X(当前稳定版:2.0.4) 中,提供了相应的解决方案,以方便我们在设计游戏时,能够更好的适应不同的环境.   而 ...

  7. js-引用类型-Array

    1.数组的操作方法 <html> <meta http-equiv="content-type" charset="utf-8" /> ...

  8. JS 函数节流和去抖

    1.什么是节流和去抖? 节流.就是拧紧水龙头让水少流一点,但是不是不让水流了.想象一下在现实生活中有时候我们需要接一桶水,接水的同时不想一直站在那等着,可能要离开一会去干一点别的事请,让水差不多流满一 ...

  9. shell自动化巡检

    #!/bin/bash#主机信息每日巡检 IPADDR=$(ifconfig eth0|grep 'inet addr'|awk -F '[ :]' '{print $13}')#环境变量PATH没设 ...

  10. 【Win 10 应用开发】将墨迹保存到图像的两种方法

    IT界最近这几年,各种乱七八糟的东西不断出现,其中能用在实际工作与生活中的,大概也就那么几个.Web 前端也冒出各种框架,这就为那些喜欢乱用框架的公司提供了很好的机会,于是造成很多项目体积越来越庞大, ...