Java - Load file, replace string, save

非 Y 不嫁゛ 提交于 2020-01-11 12:39:49

问题


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.


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/8032223/java-load-file-replace-string-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!