Java:如何轻松更改Java中的配置文件值?

Kit*_* Ho 1 java configuration

我有一个名为config.txt的配置文件,如下所示.

IP=192.168.1.145
PORT=10022
URL=http://www.stackoverflow.com
Run Code Online (Sandbox Code Playgroud)

我想用Java改变配置文件的一些值,比如将端口改为10045.我怎样才能轻松实现?

IP=192.168.1.145
PORT=10045
URL=http://www.stackoverflow.com
Run Code Online (Sandbox Code Playgroud)

在我的试用版中,我需要编写大量代码来读取每一行,找到PORT,删除原始的10022,然后重写10045.我的代码是虚拟的,难以阅读.java中有什么方便的方法吗?

非常感谢 !

Pet*_*rey 5

如果你想要一些简短的东西,你可以使用它.

public static void changeProperty(String filename, String key, String value) throws IOException {
   Properties prop =new Properties();
   prop.load(new FileInputStream(filename));
   prop.setProperty(key, value);
   prop.store(new FileOutputStream(filename),null);
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,它不保留订单或字段或任何评论.

如果你想保留订单,一次读一行也不是那么糟糕.


这个未经测试的代码将保留注释,空行和顺序.它不会处理多行值.

public static void changeProperty(String filename, String key, String value) throws IOException {
    final File tmpFile = new File(filename + ".tmp");
    final File file = new File(filename);
    PrintWriter pw = new PrintWriter(tmpFile);
    BufferedReader br = new BufferedReader(new FileReader(file));
    boolean found = false;
    final String toAdd = key + '=' + value;
    for (String line; (line = br.readLine()) != null; ) {
        if (line.startsWith(key + '=')) {
            line = toAdd;
            found = true;
        }
        pw.println(line);
    }
    if (!found)
        pw.println(toAdd);
    br.close();
    pw.close();
    tmpFile.renameTo(file);
}
Run Code Online (Sandbox Code Playgroud)