Question: 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);
    os.write(input.getBytes());

    file.close();
    os.close();
}

```

This is my file before I replace some lines

```
example1
example2
example3

```

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

```
example1example2example3

```

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?

Answer: 
If you read and modify line by line this has the advantage, that you dont need to fit the whole file in memory. Not sure if this is possible in your case, but it is generally a good thing to aim for streaming. In your case this would in addition remove the need for concatenate the string and you don't need to select a line terminator, because you can write each single transformed line with println(). It requires to write to a different file, which is generally a good thing as it is crash safe. You would lose data if you rewrite a file and get aborted.

```
private void updateLine(String toUpdate, String updated) throws IOException {
    BufferedReader file = new BufferedReader(new FileReader(data));
    PrintWriter writer = new PrintWriter(new File(data+".out"), "UTF-8");
    String line;

    while ((line = file.readLine()) != null)
    {
        line = line.replace(toUpdate, updated);
        writer.println(line);
    }
    file.close();
    if (writer.checkError())
        throw new IOException("cannot write");
    writer.close();
}

```

In this case, it assumes that you need to do the replace only on complete lines, not multiple lines. I also added an explicit encoding and use a writer, as you have a string to output.
This is because you use OutputStream which is better for handling binary data. Try using PrintWriter and don't add any line terminator at the end of the lines. Example is [here](https://stackoverflow.com/questions/2885173/java-how-to-create-and-write-to-a-file)