首页 > 编程知识 正文

java 读取配置文件,java有多少种方法

时间:2023-05-05 02:46:59 阅读:173959 作者:2827

导入. properties配置文件在实际开发中经常使用,总结起来有以下几种方法(例如:

一.通过jdk提供的java.util.Properties类。

该类继承自java.util.HashTable,并且实现了Map接口,因此可以使用正确的方法处理属性文件,但不推荐使用put和putAll这两种方法。 put方法不仅可以存储在String型value中,还可以存储在Object型value中。 因此,java.util.Properties类提供了用于处理属性文件的getProperty ()和setProperty () )方法。 此外,store或save ) (已过期)来保存属性值(将属性值写入. properties配置文件)。 在使用之前,必须加载属性文件。 有两种方法: load和loadFromXML。

load提供了两种方法的重载: load (输入流)、load (读),通过这两种方法可以加载属性文件。

InputStream可以通过以下各种方式获得:

1、用当前类加载器的getResourceAsStream方法获取

inputstream instream=test properties.class.getclass loader ().getresourceasstream (' test.properties ' );

2、从文件中获取

inputstream instream=new file inputstream (new file (' file path );

3、用类加载器获取,也和第一个一样

inputstream in=class loader.getsystemresourceasstream ('文件路径' );

4、在servlet中,也可以在context中获取InputStream

inputstream in=context.getresourceasstream (' file path );

5、通过URL获取

URLURL=newURL('path ); inputstream instream=URL.open stream (;

读取方法如下。

Properties prop=new Properties (; PROP.load(Instream ); string key=prop.getproperty (' username ); //stringkey=(string ) prop.get(username );

二.在java.util.ResourceBundle类中读取。 这个方式比使用Properties方便。

ResourceBundle.getBundle ) )通过静态方法获取(ResourceBundle是抽象类),要通过该方法获取properties属性文件,不需要给. properties添加扩展名

resourcebundleresource=resource bundle.get bundle (com/mmq/test ); //test是属性文件名,位于软件包com.mmq下,如果位于src下,则在test中保持string key=resource.getstring (' username );

2、通过InputStream读取获取InputStream的方法与上述相同。 省略说明。

resourcebundleresource=newpropertyresourcebundle;

注:使用过程中遇到的最大问题可能是配置文件的路径问题。 如果配置文件位于当前类的包下,则必须用包名称限定它。 例如,如果test.properties位于com.mmq包下,则为com/mmq/test.properties (如果属性文件位于src根目录下,则直接为test.properties )

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。