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
一:可以使用创建文本文档的方式创建将后缀名改为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
相关文章推荐
- java 解析csv
- JAVA使用POI创建EXCEL文件
- logback与Spring、SpringMVC结合使用教程
- JAVA List与数组互转
- SpringMVC 解读之<mvc:annotation-driven/>标签
- Java中的hashMap
- 学习练习 java数据库查询小题
- JavaBean 初步(一) 之 实现网页登陆
- Dubbo与Zookeeper、SpringMVC整合和使用(负载均衡、容错)
- 关于SpringMVC返回json数据的三种方式
- Java RMI 框架(远程方法调用)
- 浅析RxJava处理复杂表单验证问题的方法
- Java RMI之HelloWorld篇
- Spring框架的AOP源码剖析
- Struts2入门示例
- Java 加密PDF设置密码并添加水印
- JDK线程池源码分析
- Spring与RMI集成实现远程访问
- spring mvc的例子
- Java 加密Excel文件(打开时需输入密码)