Java - Load file, replace string, save

前端 未结 3 613
借酒劲吻你
借酒劲吻你 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<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();
    
    }
    

    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");
    
    0 讨论(0)
  • 2021-01-24 09:26

    Hard to answer without the complete code...

    Is value a string ? If so the replace will create a new string but you are not saving this string anywhere. Remember Strings in Java are immutable.

    You say you use a BufferedWriter, did you flush and close it ? This is often a cause of values mysteriously disappearing when they should be there. This exactly why Java has a finally keyword.

    Also difficult to answer without more details on your problem, what exactly are you trying to acheive ? There may be simpler ways to do this that are already there.

    0 讨论(0)
  • 2021-01-24 09:30

    I think most convenient way is:

    1. Read text file line by line using BufferedReader
    2. For each line find the int part using regular expression and replace it with your new value.
    3. Create a new file with the newly created text lines.
    4. Delete source file and rename your new created file.

    Please let me know if you need the Java program implemented above algorithm.

    0 讨论(0)
提交回复
热议问题