public class TestProperties {//创建一个带有指定默认值的空属性列表Properties properties = new Properties();FileOutputStream out =null;InputStream in = null;/*** 读取属性文件内容*/public void ReadPorp1(){//读取属性文件try {in = new BufferedInputStream(new FileInputStream("./test.properties"));properties.load(in);//将Set转成iterator来遍历Iterator<String> it =properties.stringPropertyNames().iterator();while(it.hasNext()){String key = it.next();System.out.println(key + ":" +properties.getProperty(key));/*** IcisReport.contextPath:192.168.3.143* 有错误* java.util.NoSuchElementException: Hashtable Enumerator* 下面的方法是有问题的,视频中已经讲过了!除了第一个,其他元素目标无法确定*///System.out.println(it.next() +":"+properties.getProperty(it.next()));in.close();}} catch (Exception e) {e.printStackTrace();System.out.println("读取文件报错");}}/*** 读取属性文件2*/public void ReadPorp2(){try {in = new BufferedInputStream(new FileInputStream("./test.properties"));properties.load(in);Set<String> keySet = properties.stringPropertyNames();for(String key : keySet){System.out.println(key + ":"+properties.getProperty(key));}} catch (Exception e) {e.printStackTrace();System.out.println("读取文件报错");}}/*** 写入内容到属性文件* @return*/public void WriteProp(){//保存属性到b.properties中!try {//获得test.properties的属性列表in = new BufferedInputStream(new FileInputStream("./test.properties"));properties.load(in);//以追加方式将所写数据保存属性到b.properties中!out = new FileOutputStream("./b.properties",true);properties.setProperty("hukr", "are you OK");properties.store(out, "Content--Hukr");out.close();System.out.println("写入完成");} catch (Exception e) {e.printStackTrace();System.out.println("写文件报错");}}/*** 测试程序* @param args*/public static void main(String[] args) {TestProperties testProp = new TestProperties();//testProp.ReadPorp1();//testProp.WriteProp();testProp.ReadPorp2();}}
Java学习路上之Properties!
最新推荐文章于 2025-09-03 23:14:03 发布
