方法:
Properties properties = new Properties();
FileInputStream in = new FileInputStream("**.properties");
properties.load(in);
in.close();
配置文件:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
username=root
password=
代码实现:
import java.io.FileInputStream;
import java.util.Properties;
public class PropertiesTest {
private static final String PROPERTIES_NAME = “db.properties”;
public static String DB_DRIVER = null;
public static String DB_URL = null;
public static String DB_USER = null;
public static String DB_PWD = null;
static{
FileInputStream in = null;
try{
Properties properties = new Properties();
in = new FileInputStream(PROPERTIES_NAME);
properties.load(in);
DB_DRIVER = properties.getProperty("driver");
DB_URL = properties.getProperty("url");
DB_USER = properties.getProperty("username");
DB_PWD = properties.getProperty("passworld");
System.out.println("读取配置信息成功!");
showConfig();
}catch(Exception e){
e.printStackTrace();
System.out.println("读取配置信息失败!");
}finally{
if(in != null){
try{
in.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
private static void showConfig(){
System.out.println("-----------------------配置信息-----------------");
System.out.println("dirver: "+DB_DRIVER);
System.out.println("url: "+DB_URL);
System.out.println("user: "+DB_USER);
System.out.println("passworld: "+DB_PWD);
System.out.println("----------------------------------------------");
}
public static void main(String[] args){
}
}
运行结果:
读取配置信息成功!
-----------------------配置信息-----------------
dirver: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
user: root
passworld: null
作者:qq_33608562
来源:CSDN
原文:https://blog.csdn.net/qq_33608562/article/details/73527965?utm_source=copy
版权声明:本文为博主原创文章,转载请附上博文链接!加粗样式