我的建议是,除了原始档案的所有内容(无论是记忆中还是临时档案中的内容;我是记忆中的内容),然后再次书写,包括修改内容。 我认为这项工作将:
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");