Properties文件处理方式
来源:互联网 发布:dnf软件限制策略优化 编辑:程序博客网 时间:2024/06/05 20:10
项目经常用到json,xml,properties,文本文件等,作为配置文件。用来存储连接字符串或其他配置参数等。
本文记录properties。
properties文件,存储格式 键=值。例如新建一个 config.properties文件:
####这里是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,测试输出
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不存在时,返回默认值
(完)
关于资源加载:
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的帮助类:
- Properties文件处理方式
- Properties 文件读取方式
- Properties文件的处理
- java处理properties文件
- properties文件的读取方式
- 读取properties文件的方式
- properties资源文件加载方式
- 使用 SDLX 处理 *.properties 文件
- perl处理properties文件[转]
- properties文件读取的几种方式
- Properties 文件 读取 的几种方式
- Spring使用程序方式读取properties文件
- MyEclipse修改Properties文件编码方式
- Spring使用程序方式读取properties文件
- 修改MyEclipse的Properties文件编码方式
- Spring加载properties文件指定编码方式
- 修改MyEclipse10的Properties文件编码方式
- Java 读取属性文件Properties,方式2
- redis应用学习
- SPI串行存储器
- ubuntu修改mysql 5.7 数据存储目录datadir
- jstl 问题rg.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/core cannot
- seq2seq lecture
- Properties文件处理方式
- Unity调用android的方法,android调用Unity的方法,unity和安卓的交互(2)2
- Byte、KB、B、MB、GB之间的关系
- C# 使用HttpWebRequest Post提交数据,携带Cookie和相关参数示例
- 深度学习Matlab工具箱代码注释——cnnsetup.m
- MultipartResolver实现文件上传
- error C4146: 一元负运算符应用于无符号类型,结果仍为无符号类型
- import static和import的区别
- Tpcc-MySQL测试与出图