在java类中有时我们需要对一些properties 文件进行读取
1 利用类加载器进行读取
InputStream inStream = DBOperationImpl.class.getClassLoader().getResourceAsStream("config/jdbc.properties");
Properties prop = new Properties();
prop.load(inStream);
userName = prop.getProperty("jdbc.username","root"); //设置默认值
password = prop.getProperty("jbbc.password","root");
String url = prop.getProperty("jdbc.url");
利用类加载读取时prop.getProperty(name),获取属性时我们可以为获取的属性设置默认值,若获取到的属性为空,则会去使用默认值代替
2 利用java.util.ResourceBundle类来读取
ResourceBundle resource = ResourceBundle.getBundle("config/jdbc");
userName = resource.getString("jdbc.username");
password = resource.getString("jdbc.password");
String url = resource.getString("jdbc.url");