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);
时间: 2024-09-30 06:07:05