How to overwrite a line in a .txt file using Java?


API’s used

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.

The java.util class (constructor) accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions. To read various datatypes from the source using the nextXXX() methods provided.

The StringBuffer class is a mutable alternative to String, after instantiating this class you can add data to it using the append() method.

Procedure

To overwrite a particular line of a file −

Read the contents of a file to String −

  • Instantiate the File class.

  • Instantiate the Scanner class passing the file as parameter to its constructor.

  • Create an empty StringBuffer object.

  • add the contents of the file line by line to the StringBuffer object using the append() method.

  • Convert the StringBuffer to String using the toString() method.

  • Close the Scanner object.

Invoke the replaceAll() method on the obtained string passing the line to be replaced (old line) and replacement line (new line) as parameters.

Rewrite the file contents −

  • Instantiate the FileWriter class.

  • Add the results of the replaceAll() method the FileWriter object using the append() method.

  • Push the added data to the file using the flush() method.

Example

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class OverwriteLine {
   public static void main(String args[]) throws IOException {
      //Instantiating the File class
      String filePath = "D://input.txt";
      //Instantiating the Scanner class to read the file
      Scanner sc = new Scanner(new File(filePath));
      //instantiating the StringBuffer class
      StringBuffer buffer = new StringBuffer();
      //Reading lines of the file and appending them to StringBuffer
      while (sc.hasNextLine()) {
         buffer.append(sc.nextLine()+System.lineSeparator());
      }
      String fileContents = buffer.toString();
      System.out.println("Contents of the file: "+fileContents);
      //closing the Scanner object
      sc.close();
      String oldLine = "No preconditions and no impediments. Simply Easy Learning!";
      String newLine = "Enjoy the free content";
      //Replacing the old line with new line
      fileContents = fileContents.replaceAll(oldLine, newLine);
      //instantiating the FileWriter class
      FileWriter writer = new FileWriter(filePath);
      System.out.println("");
      System.out.println("new data: "+fileContents);
      writer.append(fileContents);
      writer.flush();
   }
}

Output

Contents of the file: Tutorials Point originated from the idea that there exists a 
class of readers who respond better to online content and prefer to learn new skills.
Our content and resources are freely available and we prefer to keep it that way to 
encourage our readers acquire as many skills as they would like to.
We don’t force our readers to sign up with us or submit their details either.
No preconditions and no impediments. Simply Easy Learning!

new data: Tutorials Point originated from the idea that there exists a class of readers 
who respond better to online content and prefer to learn new skills.
Our content and resources are freely available and we prefer to keep it that way to 
encourage our readers acquire as many skills as they would like to.
We don’t force our readers to sign up with us or submit their details either.
Enjoy the free content

Updated on: 14-Oct-2019

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements