修改java中的文件

时间:2015-08-11 12:56:12

标签: java file properties

我正在尝试修改文件设置中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();
        }
    }

我必须提到该文件已存在且它有一些预设值

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

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

如果要将Properties对象的状态连接到文件,则需要显式执行此操作。

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