一、要点

1.通用方式

image.png

2.流的形式

  1. package com.xit.reflect;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.util.Properties;
  7. public class IoPropertiesTest {
  8. public static void main(String[] args) throws IOException {
  9. // String path = Thread.currentThread().getContextClassLoader().getResource("classinfo2.properties").getPath();
  10. // FileReader reader = new FileReader(path);
  11. /*
  12. 流的形式
  13. */
  14. InputStream reader = Thread.currentThread().getContextClassLoader().
  15. getResourceAsStream("classinfo2.properties");
  16. Properties pro = new Properties();
  17. pro.load(reader);
  18. reader.close();
  19. String className = pro.getProperty("className");
  20. System.out.println(className);
  21. }
  22. }

二、ResourceBundle替代IO(最终)

1、IO + Properties,怎么快速绑定属性资源文件?

  1. //要求:第一这个文件必须在类路径下<br /> //第二这个文件必须是以.properties结尾。<br /> ResourceBundle bundle = ResourceBundle.getBundle("com/bjpowernode/test");<br /> String value = bundle.getString(key);
  1. package com.xit.reflect;
  2. import java.util.ResourceBundle;
  3. public class ResourceBundleTest {
  4. public static void main(String[] args) {
  5. //资源绑定器,只能绑定xxx.properties文件。并且这个文件必须在类路径下,文件扩展名必须是properties
  6. //并且在写路径的时候,路径后面的扩展名不能写
  7. ResourceBundle bundle = ResourceBundle.getBundle("classinfo2");
  8. String className= bundle.getString("className");
  9. System.out.println(className);
  10. }
  11. }