Java - Load file, replace string, save

前端 未结 3 617
借酒劲吻你
借酒劲吻你 2021-01-24 09:07

I have a program that loads lines from a user file, then selects the last part of the String (which would be an int)

Here\'s the style it\'s saved in:

na         


        
3条回答
  •  心在旅途
    2021-01-24 09:09

    My suggestion is, save all the contents of the original file (either in memory or in a temporary file; I'll do it in memory) and then write it again, including the modifications. I believe this would work:

    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();
    
    }
    

    And you'd call the method like this, providing the File you want to modify and the name of the value you want to select:

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

提交回复
热议问题