读取properties的几种方法。

来源:互联网 发布:ncut算法matlab 编辑:程序博客网 时间:2024/06/06 07:16
public static void main(String[] args) {
String driver;
String user;
String password;
String url;
try {
Properties p1 = new Properties();
Properties p2 = new Properties();
Properties p3 = new Properties();
// 1 ResourceBundle getBundle
ResourceBundle langue = ResourceBundle.getBundle("Langue", Locale.CHINA);
System.out.println("ResourceBundle getBundle:" + langue.getObject("name"));
// 2 BufferedInputStream PropertyResourceBundle
InputStream in2 = new BufferedInputStream(new FileInputStream("d:\\config.properties"));
ResourceBundle rb = new PropertyResourceBundle(in2);
System.out.println("BufferedInputStream PropertyResourceBundle password:" + rb.getObject("password"));
// 使用java.util.Properties类的load()方法
// 3 BufferedInputStream load
InputStream inputStream = new BufferedInputStream(new FileInputStream("d:\\config.properties"));
p1.load(inputStream);
System.out.println("BufferedInputStream getBundle user:" + p1.getProperty("user"));
// 4 java.lang.ClassLoader类的getSystemResourceAsStream() load
InputStream in3 = ClassLoader.getSystemResourceAsStream("/config.properties");
p3.load(in3);
System.out.println("java.lang.ClassLoader类的getSystemResourceAsStream():" + p3.getProperty("url"));
// 5 class getResourceAsStream load
InputStream in = TestConnection.class.getResourceAsStream("/config.properties");
p2.load(in);
driver = p2.getProperty("driver");
url = p2.getProperty("url");
user = p2.getProperty("user");

password = p2.getProperty("password");

Class.forName(driver).newInstance();
DriverManager.getConnection(url, user, password);
System.out.println("class getResourceAsStream: Got the properties , connected the db.");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
0 0
原创粉丝点击