首页 > 编程知识 正文

properties如何调用(java中properties)

时间:2023-05-04 21:04:24 阅读:77215 作者:3419

前言Spring时,以XML性能分析方法配置数据库连接池时,使用==context : property-placeholder==标记进行读取。 现在,我们将使用Java的几种比较基础方法读取属性文件。

开始之前,让我先说一下目前比价常用的几种方法。

可以使用java.util.Properties类,使用其load方法加载inputStream字节流。

使用java.util.ResourceBundle类读取。

对Properties类的操作与对Map的操作有点类似,因为使用Properties类的Properties类继承自Hashtable,而Hashtable实现了Map接口。

使用Properties加载. Properties文件的主要要点是load方法。 load方法需要InputStream流。

这里常用的流获取包括:

使用当前类的ClassLoader (的getResourceAsStream ),getResourcesAsStream返回InputStream。 使用ClassLoader类的getSystemResourceAsStream (),此方法也返回InputStream。 如何使用文件输入流。 具体的例子是为了方便,我直接使用的log4j.properties。 文件的位置如下。

/**单独提取的方法直接异常*/publicvoidprintkeyvalue (inputstream inputstream ) throwsioexception )属性=new属性); properties.load(Inputstream; setobjectkeys=properties.keyset (; for(objectkey:keys ) system.out.println ) key'='properties.get ) key ); } } /*** *如果使用从当前类加载器的getResourcesAsStream检索的. Class.class.getClassLoader ().getResourcesAsStream ),请填写@throwsioexception*/@ testpublicvoidgetpropertiesfromresourceasstream () )。throwsioexception { inputstreamresourceasstream=properties utts utream rceasstream (' com/getclass loader ) }.getresourceasstream打印密钥值(resourceasstream; 要从} /*** *文件检索并使用InputStream字节*,必须将其主要命名为src。 什么是需要将路径配置准确到绝对地址级别*?这个mylog4j文件位于com/dimple/getproperityfile/my log4j.properties下,该com关闭这样的相对路径项目地址只要能够构成完全的访问地址即可* @ throwsioexception */@ testpublicvoidgetpropertiesfromfile () throwsioexception { inputstream inputstream=new file inputstream (new file (' src/com/dimple/getproperityfile/my log4j ppile ) }/* * *使用class类的getSystemResourceAsStream方法*与使用当前类的ClassLoader相同**@throwsioexception*/@ testpublicvoidgetpropertiesfrortiesfream throwsioexception { inputstreamsystemresourceasstream=class loader.getsystemremresoure 也可以通过两种方法将使用资源绑定类的资源绑定类导入到配置文件中

使用类ResourcesBundle的getBundle方法加载属性文件。 使用其派生类PropertyResourceBundle (),通过传递单个InputStream来读取数据。 代码如下。

/* * *使用Java.util.resource bundle类加载属性文件。 请注意,不需要加扩展名。 */@ testpublicvoidgetpropertiesfromresourcebundle () resourcebundle=resource bundle.get bundle ) ) com/() while(keys.hasmoreelements () ) { String s=keys.nextElement; system.out.println (s '=' resource bundle.getstring ) s ); }//* * *使用inputstream流操作的资源绑定。 获取流的方法如上所述。 *@throwsioexception*/@ testpublicvoidgetpropertiesfromresourcebundleinputstream () ) ) ) ) throwsioexception { ) stemresourceasstream (com/dimple/getproperition resourcebundle resourcebundle=newpropertyresourcebundle (系统资源调配enumerationstringkeys=resource bundle.getkeys (; while(keys.hasmoreelements () ) { String s=keys.nextElement; system.out.println (s '=' resource bundle.getstring ) s ); }以上代码总结方法具体有什么用已经很清楚了,面临的问题已经不是代码问题。 传球。 这条路,相对路,绝对路,项目路,这条路确实让人头疼。 在File的Test代码的哪里,文件路径离我尝试的很近。 当然,读者可能会说,直接拿走鼠标,可以点击是正确的。 但是在File那里,我没有加入src。 可以单击,但如果在项目错误报告中添加FileNotFound和src,则可以正常访问,但不能单击。 这是因为在IDEA中,有一个词叫“工程路径”,工程路径不包含src,代码写在src下面,因此无法达到最后的绝对路径,从而发生了错误。

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