且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-06 14:47:01

p>如果你想要的东西短,你可以使用这个。

  public static void changeProperty(String filename,String key,String value) throws IOException {
属性prop = new Properties();
prop.load(new FileInputStream(filename));
prop.setProperty(key,value);
prop.store(new FileOutputStream(filename),null);
}

不幸的是,它不保留订单或字段或任何注释。 p>

如果您想保留订单,一次读取一行不会太差。






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

  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);
}


I have a config file, named config.txt, look like this.

IP=192.168.1.145
PORT=10022
URL=http://www.***.com

I wanna change some value of the config file in Java, say the port to 10045. How can I achieve easily?

IP=192.168.1.145
PORT=10045
URL=http://www.***.com

In my trial, i need to write lots of code to read every line, to find the PORT, delete the original 10022, and then rewrite 10045. my code is dummy and hard to read. Is there any convenient way in java?

Thanks a lot !

If you want something short you can use this.

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);
}

Unfortunately it doesn't preserve the order or fields or any comments.

If you want to preserve order, reading a line at a time isn't so bad.


This untested code would keep comments, blank lines and order. It won't handle multi-line values.

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);
}