Java replace line in a text file


I found this code from another question

private void updateLine(String toUpdate, String updated) throws IOException {
    BufferedReader file = new BufferedReader(new FileReader(data));
    String line;
    String input = "";

    while ((line = file.readLine()) != null)
        input += line + "\n";

    input = input.replace(toUpdate, updated);

    FileOutputStream os = new FileOutputStream(data);


This is my file before I replace some lines


But when I replace a line, the file now looks like this


Which makes it impossible to read the file when there are a lot of lines in it.

How would I go about editing the code above to make my file look what it looked like at the start?

Best Solution

Use System.lineSeparator() instead of \n.

while ((line = file.readLine()) != null)
    input += line + System.lineSeparator();

The issue is that on Unix systems, the line separator is \n while on Windows systems, it's \r\n.

In Java versions older then Java 7, you would have to use System.getProperty("line.separator") instead.

As pointed out in the comments, if you have concerns about memory usage, it would be wise to not store the entire output in a variable, but write it out line-by-line in the loop that you're using to process the input.