在工作中,我们把自己编译好的程序打成包之后要放到对应的服务器上部署起来,部署的时候通常会带着conf.properties文件,并把这个文件与打包程序放在同级目录下,当然,同时也会有相应的指导文件和启动脚本(这个以后再说)。
把这个文件单独拿出来的优势有以下几点:
1.程序在执行的时候,会默认优先读取同级目录下的配置文件,如果同级目录下没有这个文件,就会去读取程序里的配置文件。
2.把配置值文件放在外面,提高可扩展性,如果需求改变了服务器环境,只要让运维或测试人员去修改服务器上的配置文件就可以了。
看到下面的例子你就全明白了!
步骤:
1.编写 conf.properties
#redis
redisip=192.168.0.112
redisport=6379
redispwd=yisa123456q
phone_key=drug_phone_data
bank_key=drug_bank_data
#db
dbip=192.168.2.90
dbport=8529
dbname=example
username=example
userpwd=123456
phone_docname=phone
bank_docname=bank
phone_edgename=phone_edge
bank_edgename=bank_edge
#srvdb
srvdbadd=192.168.0.14:8123
srvdbtable=cellinfo_v2.cellinfo_v2
srvuser=null
srvpwd=null
其实就是各个数据库的ip,端口什么的,一些固定值。
2.写io流读取配置文件
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Author gaofan
* Date 2020/7/21 15:10
* Version 1.0
*/
public class PropertiesUtil {
private static Logger logger = Logger.getLogger(PropertiesUtil.class);
public static Properties getProperties() {
InputStream inputStream = null;
Properties properties = null;
try {
String path = new File("").getCanonicalPath()+"/config.properties";
inputStream = new FileInputStream(path);
logger.info("配置文件路径:" + path);
properties = new Properties();
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}finally{
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return properties;
}
}
3.调用这个方法就可以了
默认返回String,如果想要int,转换一下就可以,代码里面有