当前位置: 首页 > 科技观察

Java中Properties的使用详解

时间:2023-03-18 20:45:28 科技观察

本文主要介绍Java中Properties的使用详解的相关资料。需要的朋友可以参考一下。Java中有一个比较重要的类Properties(java.util.Properties),主要用来读取Java配置文件。各种语言都有自己支持的配置文件。配置文件中的很多变量是经常变化的,所以也是为了方便用户而做的,让用户不用程序本身就可以修改相关的变量设置。今天,我们开始使用Properties。在Java中使用Properties的文档指出:Properties类表示一组持久的属性。属性可以保存到流中或从流中加载。propertylist中的每个key及其对应的value都是一个string.Propertiesclass说明:publicclassPropertiesextendsHashtable测试的工程结构如下:1.在huhx.properties文件中,为了方便我们添加一条数据:name=huhx2.加载并读取huhx.properties文件,得到相应的属性.get("姓名"));三、PropertiesPrintStream的list方法的使用printStream=System.out;properties.list(printStream);list方法的具体代码:publicvoidlist(PrintStreamout){out.println("--listingproperties--");Hashtableh=newHashtable();enumerate(h);for(Enumeratione=h.keys();e.hasMoreElements();){Stringkey=(String)e.nextElement();Stringval=(String)h.get(key);if(val.length()>40){valval=val.substring(0,37)+"...";}out.println(key+"="+val);}}四、Properties的store方法的使用OutputStreamoutputStream=newFileOutputStream("huhx.txt");properties.store(outputStream,"comments");五、PropertiesOutputStreamoutputStream2=newFileOutputStream("huhx.xml");properties.storeToXML(outputStream2,"comments");的storeToXML方法的使用六、最终生成的文件如下:huhx.txt:#comments#ThuMay1919:19:36CST2016name=huhxhuhx.xml:commentshuhx友情链接,PropertiesTest.java:packagecom.huhx.linux;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.OutputStream;importjava.io.PrintStream;importjava.util.Properties;publicclassPropertiesTest{publicstaticvoidmain(String[]args)throwsException{//一般公关属性的使用Propertiesproperties=newProperties();FileInputStreamfis=newFileInputStream("huhx.properties");properties.load(fis);System.out.println(properties.get("name"));//下面是部分测试PrintStreamprintStream=System.out;properties.list(printStream);OutputStreamoutputStream=newFileOutputStream("huhx.txt");properties.store(outputStream,"comments");OutputStreamoutputStream2=newFileOutputStream("huhx.xml");properties.storeToXML(outputStream2,"comments");}}以上就是小编为大家介绍的Java中Properties的使用详解。希望对您有所帮助。如果您有任何问题,请给我留言,小编会及时回复您,非常感谢您对脚本之家的支持!