Java读取Preperties的文件方式有很多,这里只列了5种,举例如下:
方式一:
|
1
2
3
|
Properties property =newProperties();property.load(newFileInputStream("你的文件位置"));//需要指定文件具体位置,如果是web项目,则要指定要WEB-INF/classes下String value = property.getProperty("你的属性的key"); |
方式二:
|
1
2
3
4
5
|
Properties prop =null;InputStream is;prop =newProperties();is = Constants.class.getResourceAsStream("/test.properties");// 需要加/prop.load(is); |
方式三:
|
1
2
3
4
|
ResourceBundle rb = ResourceBundle.getBundle("test", Locale.getDefault());String s = rb.getString("PATH");
不加/,也不加 .properties, |
用ResourceBundle读取.properties文件可避免路径问题
方式四:
|
1
2
3
4
5
6
|
Properties prop =null;InputStream is;prop =newProperties();is = Constants.class.getClassLoader().getResourceAsStream("test.properties");// 不需要加/prop.load(is);returnprop.getProperty("PATH"); |
方式五:
|
1
2
3
|
InputStream in = ClassLoader.getSystemResourceAsStream("test.properties");Properties p =newProperties();p.load(in); |
本文介绍了在Java中读取Properties配置文件的五种常见方式,包括使用FileInputStream、Class.getResourceAsStream、ResourceBundle、Class.getClassLoader及ClassLoader.getSystemResourceAsStream等方法,并提供了具体的代码示例。
204

被折叠的 条评论
为什么被折叠?



