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

java中配置文件的用法

2016-06-13 10:42 330 查看
首先在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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: