user1032232
user1032232

Reputation: 47

Java - Load file, replace string, save

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:

nameOfValue = 0
nameOfValue2 = 0

and so on. I have selected the value for sure - I debugged it by printing. I just can't seem to save it back in.

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

How would I resave it? I've tried bufferedwriter but it just erases everything in the file.

Upvotes: 1

Views: 15331

Answers (3)

Óscar López
Óscar López

Reputation: 236004

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");

Upvotes: 5

Newtopian
Newtopian

Reputation: 7712

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.

Upvotes: 0

Upul Bandara
Upul Bandara

Reputation: 5958

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.

Upvotes: 1

Related Questions