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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值