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

我有一个程序从用户文件加载行,然后选择字符串的最后一部分(这将是一个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但它只删除了文件中的所有内容。

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

 public static void replaceSelected(File file, String type) throws IOException { // we need to store all the lines List lines = new ArrayList(); // 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. 使用BufferedReader逐行读取文本文件
  2. 对于每一行,使用正则表达式查找int部分,并将其替换为新值。
  3. 使用新创建的文本行创建新文件。
  4. 删除源文件并重命名新创建的文件。

如果您需要上面实现的Java程序,请告诉我。

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

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

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

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