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

use*_*232 1 java string file-io replace properties

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

这是它保存的样式:

nameOfValue = 0
nameOfValue2 = 0
Run Code Online (Sandbox Code Playgroud)

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

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

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

Ósc*_*pez 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();

}
Run Code Online (Sandbox Code Playgroud)

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

replaceSelected(new File("test.txt"), "nameOfValue2");
Run Code Online (Sandbox Code Playgroud)