修改 java 中的文件

modify file in java

我正在尝试修改文件设置中ip对应的值。在控制台中,它在我调用 changeIp() 后打印出我想要的结果,但它不会更改文件

这是我所做的:

public class Settings {
    public static void main(String[] args){
        changeIp("abc");
    }
    public static void changeIp(String ip) {
        Properties ps = new Properties();
        // Create the file object
        File fileObj = new File("settings.txt");
        try {
            FileInputStream fis = new FileInputStream(fileObj);
            ps.load(fis);
            ps.put("ip", ip);
            System.out.println("Get A:" + ps.getProperty("ip"));

        } catch (Exception err) {
            err.printStackTrace();
        }
    }

我不得不提一下,该文件已经存在并且它有一些预设值

您必须使用 Properties.store() 将属性写入文件。

OutputStream os = new FileOutputStream("output-file-name.properties");
ps.store(os, "");

ps.put("ip",ip) 更新位于堆上的 Properties 对象的值,而不是硬盘驱动器文件中的值。

如果您想将 Properties 对象的状态连接到文件,您需要明确地进行。

因此,就像 ps.load(fis) 负责将状态从源加载到 Properties 对象一样,ps.store(output,comment) 可用于将属性的状态存储在可能指向文件的所需输出流中.