Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java replace line in a text file

Tags:

java

file-io

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?

like image 214
user3879542 Avatar asked Aug 09 '14 15:08

user3879542


People also ask

How do you update a text file in Java?

Step 1 : Create a File object by passing the path of the file to be modified. Step 2 : Initialize oldContent with an empty string. This String object will hold all the old content of the input text file. Step 3 : Create BufferedReader object to read the input text file line by line.

How do you replace a character in a file in Java?

The replaceAll() method of the String class accepts two strings representing a regular expression and a replacement String and replaces the matched values with given String.


1 Answers

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.

like image 66
Robby Cornelissen Avatar answered Oct 04 '22 20:10

Robby Cornelissen