您的位置:首页 > 编程语言 > Java开发

Java 读取Properties配置文件

2017-06-21 10:58 357 查看
方法:
Properties properties = new Properties();
FileInputStream in = new FileInputStream("**.properties");
properties.load(in);
in.close();
配置文件:
driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8username=rootpassword=
代码实现:
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.Driverurl: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8user: rootpassworld: null----------------------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java