user3211165
user3211165

Reputation: 235

Replacing a line in a new textfile

I have a textfile with several lines.

Line 1
Line 2
Line 3
Line 4
...

I am trying for example to replace line 3 with a new sentence.

I tred using the code below, but instead of replacing it, it just adds the new sentence next to it and the rest of the text as well. I need it to be removed and place the new sentence in the same spot, and then continue the writing of the rest of the lines. What should I fix?

try {
    PrintWriter out = new PrintWriter(new FileWriter(filenew, true));
    Scanner scanner = new Scanner(file);

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (line.contains(line 2)) {        
            line = line.replaceAll("", "new sentence");
        }  
        out.write(line);
        out.write("\n");
    }   

    out.flush();
    out.close();
    scanner.close();
} 
catch (IOException e)  {
    e.printStackTrace();
}

Thanks in advance!

Upvotes: 0

Views: 54

Answers (2)

Raffaele
Raffaele

Reputation: 20885

The loop you are looking for is something like

String targetText = "... the text to search";
String replacement = "The new text";
PrintWriter out = mkPrintWriter(/*...*/);

while (in.hasNextLine()) {
  String line = in.nextLine();
  if (line.equals(targetText)) {
    out.println(replacement);
  } else {
    out.println(line);
  }
}

Note that the out file is a temporary resource. After processing, you can unlink the old file and rename the temp file.

Upvotes: 2

Szarpul
Szarpul

Reputation: 1571

Change

line = line.replaceAll("", "new sentence");

to

line = line.replaceAll(line 2, "new sentence");

Upvotes: -1

Related Questions