转载:读取.properties配置文件

一、前言                              

Java工程中想log4j、数据库连接等配置信息一般都写在.properties文件中,那么如何读取这些配置信息呢?下面把相关方法记录下来供以后查阅。

 

二、.properties文件                        

配置文件的一种,内容以键值对的形式存在,且每个键值对独占一行。#号作为行注释的起始标志,中文注释会自动进行unicode编码。示例:

# ip and port of server socket
ip=127.0.0.1
port=9999
# error message
msg=I'm sorry, bye bye!

假设上述内容存储在config.properties文件下,且bin目录结果如下:

  bin

|– main

|– Demo.class

|– config.properties

后续章节的示例将以上述内容作为目标对象来操作。

 

三、通过 Properties对象 操作                    

读取属性,示例:

复制代码
public class Demo{
  public static void main(String[] args){
    Properties props = new Properties();
    
    InputStream in = Demo.class.getResourceAsStream("../config.properties");

    // 或使用文件输入流(不推荐),假设当前工作目录为bin
    //InputStream in = new FileInputStream("./config.properties");

    props.load(in);
    in.close();
    
    // 读取特定属性
    String key = "ip";
    String ip = props.getProperty(key);

    // 遍历所有属性,方式一
    Set keys = props.keySet();
    for (Interator it = keys.iterator(); it.hasNext();){
        String k = it.next();
        System.out.println(k + ":" + props.getProperty(k));
    }
     // 遍历所有属性,方式二
    Enumeration en = props.propertyNames();
    while (en.hasMoreElements()){
        String k = en.nextElement();
        System.out.println(k + ":" + props.getProperty(k));
    }
  }
}
复制代码

1. 通过 Demo.class.getResourceAsStream(“../config.properties”); 读取配置文件,配置文件的相对路径以类文件所在目录作为当前目录。

2. 通过 new FileInputStream(“./config.properties”); 读取配置文件,配置文件的相对路径以工作目录(可以通过 System.getProperty(“user.dir”) 获取工作目录)作为当前目录。

注意:上述两种方式获取的配置文件均没有被缓存。每次都要重新加载配置文件。

写属性,示例:

复制代码
Properties props = new Properties();
InputStream in = getClass().getResouceAsStream("properties文件相对于当前类加载路径的文件目录");
props.load(in);

OutputStream output = new FileOutputStream("properties文件路径");
props.setProperty("ip", "10.248.112.123"); // 修改或新增属性键值对
props.store(output, "modify ip value"); // store(OutputStream output, String comment)将修改结果写入输出流
output.close()
复制代码

 

四、通过 ResourceBundle对象 操作                    

通过该方式仅能读取配置文件而已,不能进行写操作。示例:

// ResourceBundle rb = ResourceBundle.getBundle("配置文件相对工程根目录的相对路径(不含扩展名)");
ResourceBundle rb = ResourceBundle.getBundle("config");
try{
    String name = rb.getString("name");
}
catch(MissingResourceException ex){

注意:上述方式会缓存配置文件信息,后续读取时均是读取缓存中的内容,若在此期间修改了配置内容是无法实时同步的

ResourceBundle有两个子类ListResourceBundle和PropertyResourceBundle,在读取properties文件时实际上是使用PropertyResourceBundle来处理。

题外话:

ResourceBundle主要用于解决国际化和本地化问题。通过资源命名定义各语言和方言的信息,然乎程序在运行时获取当前本地化信息,并根据本地化信息加载相应的资源完成本地化。

资源命名规范:

复制代码
// 仅含家族名
MyResource

// 含家族名和语言
MyResource_en

// 含家族名、语言和国家
MyResource_en_US
复制代码

对应的Java代码:

// ResourceBundle首先会根据语言和国家的本地化信息去查找资源(假设现在要查找MyResource_zh_CN),当找不到时就会找MyResource_zh,再找不到就用MyResource。
ResourceBundle rb = ResourceBundle.getBundle("MyResource", Locale.getDefault())

 

五、总结                              

当然方式不止这些啦,日后继续补充!

尊重原创,转载请注明来自:http://www.cnblogs.com/fsjohnhuang/p/3995386.html  ^_^肥仔John

 

六、参考                              

http://www.cnblogs.com/panjun-Donet/archive/2009/07/17/1525597.html

java路径问题-getClass().getResourceAsStream()

src(源文件夹)

┣━11.properties

┗━myspider(myspider包)

┣━22.properties
┗━Test.java

 

Java代码  收藏代码
  1. package myspider;
  2. import java.io.UnsupportedEncodingException;
  3. /**
  4.  *
  5.  * @author mark
  6.  */
  7. public class Test {
  8.     public static void main(String[] args) throws UnsupportedEncodingException{
  9.         Test t=new Test();
  10.         //文件名前不加“/”,则表示从当前类所在的包下查找该资源。如下则表示的是从包myspider下查找22.properties文件资源。
  11.         System.out.println(“1:”+t.getClass().getResourceAsStream(“22.properties”));//输出java.io.BufferedInputStream@61de33
  12.         //文件名前加了“/”,则表示从类路径下也就是从classes文件夹下查找资源,如下表示从classes文件夹下查找22.properties文件资源。
  13.         System.out.println(“2:”+t.getClass().getResourceAsStream(“/22.properties”));//输出null
  14.         //文件名前加了“/”,则表示从类路径下也就是从classes文件夹下查找资源,如下表示从classes文件夹下查找11.properties文件资源。
  15.         System.out.println(“3:”+t.getClass().getResourceAsStream(“/11.properties”));//输出java.io.BufferedInputStream@14318bb
  16.         System.out.println();
  17.         //当前包路径4:file:/E:/myobject/myspider/build/classes/myspider/
  18.         System.out.println(“4:”+t.getClass().getResource(“”));
  19.         //输出当前类路径5:file:/E:/myobject/myspider/build/classes/
  20.         System.out.println(“5:”+t.getClass().getResource(“/”));
  21.         /*
  22.          * 如果类路径下的当前包有22.properties文件,则输出6:file:/E:/myobject/myspider/build/classes/myspider/22.properties
  23.          * 否者输出源文件下的22.properties文件的路径,则输出:6:file:/E:/myobject/myspider/src/myspider/22.properties
  24.          */
  25.         System.out.println(“6:”+t.getClass().getResource(“22.properties”));
  26.         /*
  27.          * 如果类路径下有11.properties文件,则输出7:file:/E:/myobject/myspider/build/classes/11.properties
  28.          * 否者输出源文件下的11.properties文件的路径,则输出:6:7:file:/E:/myobject/myspider/src/11.properties
  29.          */
  30.         System.out.println(“7:”+t.getClass().getResource(“/11.properties”));
  31.     }
  32. }

SystemConfig实现之从properties文件读取数据

根据从网上找的资料,使用properties类实现了读取配置文件信息。

import java.io.File;

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

/**
*/
public class SystemConfig {

private SystemConfig(){

}

//获取环境变量init.conf.env
private static final String ENV=System.getProperty(“init.conf.env”);
//构建配置文件名
private static final String MQ_ARTICLE_PROPERTY_FILE = “mq-article-“+ENV+”.properties”;

private static Properties props = null;

/**
* 初始化ResourceBundle对象
* @throws IOException
*/
private static void init() throws IOException{
if( null == props){
props = new Properties();
loadFile();
}
}

/**
* 加载指定名称的properties文件,约定路径为/conf/
* @param propName
* @throws IOException
*/
private static void loadFile() throws IOException{
//获取配置文件列表/conf/*.properties
File dir = new File(SystemConfig.class.getResource(“/”).getPath()+”conf/”);
String[] fileNames = dir.list();

//过滤出符合当前环境的文件
//List<String> fileList = null;
if (fileNames != null && fileNames.length > 0) {
//fileList = Lists.newArrayList();
// 包括文件,文件夹的判断
for (String fName : fileNames) {
if (fName.indexOf(ENV) != -1) {
//fileList.add(fName);
//load进props
InputStream in = SystemConfig.class.getResourceAsStream(“/conf/” + fName);
props.load(in);
}
}
}
}

/**
* 获取系统配置
* @param key
* @param defaultValue
* @return
*/
public static String getProperties(String key,String defaultValue){
try {
init();
} catch (IOException e) {
props = null;
}
if(null == props)
return defaultValue;
return props.getProperty(key) == null ? defaultValue : props.getProperty(key);
}

}

除了使用properties类的方法外,Java还提供了resourcebundle的方式实现这一功能。

但是resourcebundle的命名规则有约束,主要为了实现国际化。这里还是先不用这个了。知道能实现即可。