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

java中加载properties的几种方式

2015-10-31 11:02 381 查看
1. 使用java.util.Properties类的load()方法(注意点:jdbc.properties这个文件若以此种方式加载,必须要放在类路径下,不然将无法进行加载)

InputStream inputStream = new BufferedInputStream(new   FileInputStream(new File("jdbc.properties")));
Properties properties =new Properties();
properties.load(inputStream);
System.out.println(properties.get("jdbc.url"));


2. 使用java.util.ResourceBundle类的getBundle()方法(注意点:文件的写入并没有文件的后缀名)

ResourceBundle rb = ResourceBundle.getBundle("jdbc",Locale.getDefault());
Enumeration<String> keys = rb.getKeys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
System.out.println(rb.getString(key));
}


3. 使用java.util.PropertyResourceBundle类的构造函数

InputStream inputStream = new BufferedInputStream(new FileInputStream("src/jdbc.properties"));
ResourceBundle bundle =new PropertyResourceBundle(inputStream);
System.out.println(bundle.getString("jdbc.url"));


4. 使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法

InputStream inputStream = ClassLoader.getSystemResourceAsStream("jdbc.properties");
Properties properties =new Properties();
properties.load(inputStream);
System.out.println(properties.get("jdbc.url"));


5. 使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法

InputStream inputStream = JDBCProperties.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties =new Properties();
properties.load(inputStream);
System.out.println(properties.get("jdbc.url"));


6. 使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法

InputStream inputStream = JDBCProperties.class.getResourceAsStream("/jdbc.properties");
Properties properties =new Properties();
properties.load(inputStream);
System.out.println(properties.get("jdbc.url"));


7. Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法

InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: