首页 > Java基础 > JAVA读取PROPERTIES配置文件
2017
12-25

JAVA读取PROPERTIES配置文件

项目经常用到json,xml,Properties,文本文件等,作为配置文件。用来存储连接字符串或其他配置参数等。

本文记录properties。

properties文件,存储格式 键=值。例如新建一个 config.properties文件:


1
2
3
4
5
6
7
8
####这里是config.properties文件,存储数据库信息####
#数据库ip
connip=192.168.10.29
username=      user1
password=pwd1
#username=    user2
#password=test2
user="user1"

properties文件特点:

1,键值对格式

2,=等号后面,值前面,的空格,会自动忽略掉

3,值后面的空格,不会忽略

4,=等号后面的双引号,不会忽略

5,#井号后面内容,为注释,忽略

所以,读取config.properties,通过key获取值,得到结果为:

connip为[192.168.10.29]

username为[user1]

password为[pwd1 ? ?] ? 这里要注意,pwd1后面有空格

user为[“user1”] 这里要注意,值,包括双引号。

java中操作properties的类为,Java.util.Properties。

读取properties的方法,比较简单

三步:

1,加载资源; 2,通过key获取值; 3,测试输出

1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) throws IOException {
    Properties properties = new Properties();
    InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties");
    properties.load(inputStream);
 
    String result1 = properties.getProperty("connip");
    String result2 = properties.getProperty("sdfds", "error");
 
    System.err.println(result1);
    System.err.println(result2);
}

输出结果为:

192.168.10.29

error

 

程序说明:

1、资源加载

Thread.currentThread().getContextClassLoader().getResourceAsStream(“config.properties”);

这里用到了这个格式资源加载方式。

 

2、properties注意getProperty,有一个重载。

一个是直接获取值

另一个是当key不存在时,返回默认值

(完)

 

关于资源加载:

1
2
3
4
5
6
7
8
9
10
11
public class PropertiesTest {
    public static void main(String[] args) throws IOException {
        String path1 = Thread.currentThread().getContextClassLoader().getResource(".").getPath();
        String path2 = PropertiesTest.class.getClassLoader().getResource(".").getPath();
        String path3 = PropertiesTest.class.getResource(".").getPath();
 
        System.err.println("path1:" + path1);
        System.err.println("path2:" + path2);
        System.err.println("path3:" + path3);
    }
}

输出:

path1:/G:/alljavaprojece/myeclipse10project/mydemo2/bin/

path2:/G:/alljavaprojece/myeclipse10project/mydemo2/bin/

path3:/G:/alljavaprojece/myeclipse10project/mydemo2/bin/my/properties/

 

乱码

properties读取乱码解决方法

本文》有 0 条评论

留下一个回复