我们可以在运行时更新.properties文件 [英] can we update .properties file at runtime

查看:68
本文介绍了我们可以在运行时更新.properties文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



如何在运行时更新.properties文件?

在该文件中我存储了数据库配置和我想在运行时更改数据库名称,数据库用户名等数据库配置。

我无法做到这一点。如果有人知道,请告诉我。

Hi All,

how to update the .properties file at runtime?
In that file I have stored database configuration and I want to change the
database configuration like database name,database user name,etc at runtime.
I am not able to do this.Please let me know if anyone knows.

推荐答案



java中有专用的类来处理属性:java.util.Properties

请查看 javadoc [ ^ ]了解更多信息。

以下是使用示例:



Hi,
There is dedicated class in java to handle properties: java.util.Properties
Look at javadoc[^]for more information.
Here is example of use:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesTest {

  public static void main(String[] args)  {
    Properties props = new Properties();

    String propsFileName = "./src/myconfig.properties";
    try {
      //first load old one:
      FileInputStream configStream = new FileInputStream(propsFileName);
      props.load(configStream);
      configStream.close();

      //modifies existing or adds new property
      props.setProperty("connection", "new connection settings go here");
      props.setProperty("newProperty", "newValue");

      //save modified property file
      FileOutputStream output = new FileOutputStream(propsFileName);
      props.store(output, "This description goes to the header of a file");
      output.close();

    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}


HI,

但如果我运行相同的代码在服务器上,它给我一个错误,如没有这样的文件或目录。

but if I run the same code on server it gives me error like No such file or directory.


这篇关于我们可以在运行时更新.properties文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆