假如有一个文本文件,名字是jdbc.properties,它里面的内容如下:
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost
username = root
password = root
dbname = test
可以使用以下Java代码读取并打印出来:
package ione.core.login;
import java.util.Properties;
import java.io.IOException;
public class LoadJDBCProperties {
public static void main(String[] args) {
//Properties类用于操作以<key,value>形式保存数据的文件,在该文件key和value的联系使用等号“=”来表示,一行表示一对<key,value>,
//如:username = root
Properties pro = new Properties();
try {
//getResourceAsStream()是java.lang.Class类的一个方法,它通过一个给定的名字和数据流方式获取资源
//getResourceAsStream()的用法:编译好的类文件名.getResourceAsStream(),即classname.class.getResourceAsStream()
pro.load(LoadJDBCProperties.class.getResourceAsStream("jdbc.properties"));
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println("driver\t=" + pro.getProperty("driver"));
System.out.println("username=" + pro.getProperty("username"));
System.out.println("password=" + pro.getProperty("password"));
System.out.println("dbname\t=" + pro.getProperty("dbname"));
System.out.println("url\t=" + pro.getProperty("url") + "/" + pro.getProperty("dbname") + "?" +
"user=" + pro.getProperty("username") + "&" + "password=" + pro.getProperty("password"));
}//End of main
}
打印结果如下:
driver =com.mysql.jdbc.Driver
username=root
password=root
dbname =test
url =jdbc:mysql://localhost/test?user=root&password=root