java中配置文件的用法

来源:互联网 发布:学软件开发好吗 编辑:程序博客网 时间:2024/05/29 09:53

首先在java中创建配置文件有两种方式

一:可以使用创建文本文档的方式创建将后缀名改为properties文件

二:可以在eclipse中直接创建new-file文件命名为*.properties文件

*.properties文件中写的是链接数据库的属性。文件的内容是键-值得格式

其中:encrypt.algorithm是加密属性

用一个例子说明properties的使用

public static Connection getConnection() {
Connection con = null;//创建链接

Properties properties = new Properties();
//Thread.currentThread()获取当前运行的线程currentThread()是static的,只是返回当前线程对象。
InputStream in = Thread.currentThread().getClass().getResourceAsStream("/database.properties");
try {
//properties.load(new FileInputStream("/database.properties"));
properties.load(in);

String driver = properties.getProperty("driver");

if(driver != null){
System.setProperty("jdbc.drvers", driver);
}

String url = properties.getProperty("jdbc.url");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
try {
con = DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}


return con;


}
}


如果*.properties文件直接放在src目录下在获取文件路径的时候可以使用/database.properties

1 0