Java web基操 —读取配置文件
举个例子,读取下面这样一份配置文件;
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:****/table?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
jdbc.user=root
jdbc.pass=root
Java代码如下:
public class PropertiesUtil {
//首先肯定是创建一个Properties对象了
private static Properties properties = new Properties();
//赋值对应配置文件的路径
private static String config = "../jdbc.properties";
//创建一个配置文件的输入流
//当然,这里直接new一个输入流也是可行的,但比起反射来说还是有所缺陷
private static InputStream is = PropertiesUtil.class.getResourceAsStream(config);
//接下来定义一些成员属性,用来接收配置文件的值
public static String driver;
public static String url;
public static String user;
public static String pass;
static {
try {
//把流加载到Properties对象
properties.load(is);
//接下来就可以使用Properties对象的getProperty方法来获取对应的值了
driver = properties.getProperty("jdbc.driver");
url = properties.getProperty("jdbc.url");
user = properties.getProperty("jdbc.user");
pass = properties.getProperty("jdbc.pass");
} catch (IOException e) {
e.printStackTrace();
}
}
}