|
![]() |
名片设计 CorelDRAW Illustrator AuotoCAD Painter 其他软件 Photoshop Fireworks Flash |
|
近日写一个小工具,其中要用的一写配置信息,我存放在config.properties文件中。属性文件示例如下: // config.properties setting1=value1 other=other value 并写一个界面设置属性,保存。保存的操作如下: private void saveProperties() throws SystemException{ Properties prop = new Properties(); FileOutputStream fos; FileInputStream fis; try { fis = new FileInputStream(new File("." + File.separator + "config.properties")); fos = new FileOutputStream(new File("." + File.separator + "config.properties")); } catch (FileNotFoundException ex) { ex.printStackTrace(); throw new SystemException("File config.properties NOT found!"); } try { prop.load(fis); } catch (IOException ex1) { ex1.printStackTrace(); throw new SystemException("Error while read from config.properties!"); } log.debug("other is:" + prop.getProperty("other")); //返回null prop.setProperty("setting1", "value2"); //log.debug("other is:" + prop.getProperty("other")); //save the properties try { prop.store(fos, null); } catch (IOException e) { e.printStackTrace(); throw new SystemException("Error when save the config.properties."); } } 上面代码中,首先读入config.properties文件,并装载到Properties对象中。然后,设置setting1的值为value2,然后调用Properties.store()方式保存修改。然而,在使用过程中,发现在保存后的config.properties文件中,other原来的设置总是被抹掉。config.properties文件变为: //config.properties setting1=value2 后将代码中从config.properties中获取输出流放置到Properties的load方式之后,发现运行正常。估计原因可能是在load属性之前,构造了新的输出流,并且输出流的文件和输入流文件同名,造成load属性时,此时的输入流的指向已经不是实际的原来的config.properties文件,而变成了内存中由输出流产生的空的config.properties了。其中的运行机理还是不甚明朗,请对IO认识的朋友回贴赐教。 修改后的代码如下: private void saveProperties() throws SystemException{ Properties prop = new Properties(); FileOutputStream fos; FileInputStream fis; try { fis = new FileInputStream(new File("." + File.separator + "config.properties")); } catch (FileNotFoundException ex) { ex.printStackTrace(); throw new SystemException("File config.properties NOT found!"); } try { prop.load(fis); } catch (IOException ex1) { ex1.printStackTrace(); throw new SystemException("Error while read from config.properties!"); } log.debug("other is:" + prop.getProperty("other"));//返回other value prop.setProperty("setting1", "value2"); log.debug("other is:" + prop.getProperty("other")); try { fos = new FileOutputStream(new File("." + File.separator + "config.properties")); } catch (FileNotFoundException ex) { ex.printStackTrace(); throw new SystemException("File config.properties NOT found!"); } //save the properties try { prop.store(fos, null); } catch (IOException e) { e.printStackTrace(); throw new SystemException("Error when save the config.properties."); } } 返回类别: 教程 上一教程: JDK1.2关于JDBC中文问题的解决方案 下一教程: JDBC之接口技术 您可以阅读与"存储.PROPERTIES文件的一个问题"相关的教程: · ~~~用properties文件实现国际化与本地化的一个小例子~~~ · 关于使用文本域(TEXTAREA)的一个问题 · 一个向数据库存取IMAGE文件的JSP程序 · java日记(3) 类的初始化问题(CSDN一个问题有感) · 部署OGSA-DAI的Quickview client时的一个小问题 |
![]() ![]() |
快精灵印艺坊 版权所有 |
首页![]() ![]() ![]() ![]() ![]() ![]() ![]() |