读取配置文件

方式一:使用java.util.Properties类的load()方法

InputStream in =  this.getClass().getClassLoader().getResourceAsStream("conf.properties");
Properties p = new Properties();
p.load(in);
p.getProperty("name1");

方法二:使用java.util.ResourceBundle类的getBundle()方法

ResourceBundle bundle = ResourceBundle.getBundle("conf");
bundle.getString("name1");

补充:

Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法
InputStream in = context.getResourceAsStream(path);  
Properties p = new Properties(); 
p.load(in); 

区别:一般来说,ResourceBundle类通常是用于针对不同的语言来使用的属性文件。而如果你的应用程序中的属性文件只是一些配置,并不是针对多国语言的目的。那么使用Properties类就可以了。这两个类都是读取properties格式的文件的,而Properties同时还能用来写文件。

你可能感兴趣的:(java,servlet)