Java - 加载文件,替换字符串,保存

时间:2011-11-07 02:41:08

标签: java string file-io properties replace

我有一个程序从用户文件加载行,然后选择字符串的最后一部分(这将是一个int)

以下是保存的样式:

nameOfValue = 0
nameOfValue2 = 0

等等。我确定选择了这个值 - 我通过打印调试了它。我似乎无法将其保存回来。

if(nameOfValue.equals(type)) {
        System.out.println(nameOfValue+" equals "+type);
            value.replace(value, Integer.toString(Integer.parseInt(value)+1));
        }

我将如何重新保存?我尝试过bufferedwriter,但它只删除了文件中的所有内容。

3 个答案:

答案 0 :(得分:5)

我的建议是,保存原始文件的所有内容(在内存或临时文件中;我将在内存中执行),然后再次写入,包括修改。我相信这会奏效:

public static void replaceSelected(File file, String type) throws IOException {

    // we need to store all the lines
    List<String> lines = new ArrayList<String>();

    // first, read the file and store the changes
    BufferedReader in = new BufferedReader(new FileReader(file));
    String line = in.readLine();
    while (line != null) {
        if (line.startsWith(type)) {
            String sValue = line.substring(line.indexOf('=')+1).trim();
            int nValue = Integer.parseInt(sValue);
            line = type + " = " + (nValue+1);
        }
        lines.add(line);
        line = in.readLine();
    }
    in.close();

    // now, write the file again with the changes
    PrintWriter out = new PrintWriter(file);
    for (String l : lines)
        out.println(l);
    out.close();

}

你可以调用这样的方法,提供你想要修改的文件和你想要选择的值的名称:

replaceSelected(new File("test.txt"), "nameOfValue2");

答案 1 :(得分:1)

我认为最方便的方法是:

  1. 使用BufferedReader
  2. 逐行阅读文本文件
  3. 对于每一行,使用正则表达式查找int部分并替换 它带有你的新价值。
  4. 使用新创建的文本行创建新文件。
  5. 删除源文件并重命名新创建的文件。
  6. 如果您需要上面实现的Java程序,请告诉我。

答案 2 :(得分:0)

没有完整的代码很难回答......

值是字符串吗?如果是这样,替换将创建一个新字符串,但您不是在任何地方保存此字符串。记住Java中的字符串是不可变的。

你说你使用BufferedWriter,你是否冲洗并关闭它?这通常是价值在他们应该存在时神秘地消失的原因。这就是为什么Java有一个finally关键字。

如果没有关于你的问题的更多细节,也很难回答,你究竟想要实现什么?可能有更简单的方法可以做到这一点。