
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Overwrite a Line in a TXT File Using Java
The given task is to overwrite a line in a .txt file with new content. Assume we have a .txt file with the following content -
Line 1: Hello World Line 2: This is a test file. Line 3: This line will be overwritten. Line 4: Goodbye!
We want to overwrite line 3 with "This line has been changed". Following will be the resultant content -
line 1: Hello World line 2: This is a test file. line 3: This line has been changed. line 4: Goodbye!
Overwriting a Line in a ".txt" File
There are no direct methods in Java to overwrite the contents of a text file. We just need to -
- Read the contents of a file using File Readers or any other classes that accept a File as input and read its content.
- Replace the required lines.
- Write the result back to the file.
We can achieve this using various classes for each task (read from file, replace, and write back). In here, we are providing two ways -
- Using Scanner & File Writer
- Using Files.readAllLines() & Files.write() Method
Using Scanner & File Writer
The java.util.Scanner class reads all the primitive data types and Strings (from the given source), token by token. We can read the contents of the source using the methods of this class. One of the constructors of this class accepts a File as a parameter and reads its contents.
We can use the replaceAll() method of the String Class to replace a substring in the current string with another. The StringBuffer class is a mutable alternative to String, you can add data to it using the append() method.
The FileWriter class is used to write contents back to the original file. To replace the contents of a file, follow the steps given below -
Step 1: Read the contents of a file into a String
To read the contents of a file into a String -
- Instantiate the File class.
- Instantiate the Scanner class by passing the file object as a 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 a String using the toString() method.
- Close the Scanner object.
Step 2: Replace the Lines
Invoke the replaceAll() method on the obtained string, passing the line to be replaced (old line) and the replacement line (new line) as parameters.
Step 3: Write back to the file
Rewrite the file contents by following these steps -
- Instantiate the FileWriter class.
- Add the results of the replaceAll() method to the FileWriter object using the append() method.
- Push the added data to the file using the flush() method.
Example
Following is the Java program which rewrites certain lines of a file using the Scanner & FileWriter classes -
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class OverwriteLine { public static void main(String[] args) { String filePath = "D://input.txt"; String oldLine = "No preconditions and no impediments. Simply Easy Learning!"; String newLine = "Enjoy the free content"; try ( Scanner sc = new Scanner(new File(filePath)); ) { StringBuilder buffer = new StringBuilder(); while (sc.hasNextLine()) { buffer.append(sc.nextLine()).append(System.lineSeparator()); } String fileContents = buffer.toString(); System.out.println("Contents of the file:\n" + fileContents); // Replace using String.replace (literal) fileContents = fileContents.replace(oldLine, newLine); System.out.println("\nNew data:\n" + fileContents); // Write back try (FileWriter writer = new FileWriter(filePath)) { writer.write(fileContents); } } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } } }
Following is the output of the above program -
Contents of the file: Welcome to Tutorials Point. No preconditions and no impediments. Simply Easy Learning! This is an example file. New data: Welcome to Tutorials Point. Enjoy the free content This is an example file.
Using Files.readAllLines() & Files.write() Method
The Files.readAllLines() method of the Files class accepts a Path object as a parameter and reads all the lines of the file represented by the specified path into a list object.
We can go through each element of a list and, using a for loop, compare it with the line to be replaced and change it using the set() method.
The Files.write() method accepts a list and a Path object as parameters and writes the given contents to the specified file. Following are the steps to overwrite a line in a ".txt" file using the Files.readAllLines() and Files.write() method -
Step 1: Read the contents of a file into a List
To read the contents of a file into a List -
- Create a Path object using Paths.get() with the file location.
- Read all lines from the file into a List using Files.readAllLines().
Step 2: Replace the Lines
To replace the lines -
- Loop through the list and look for the line you want to change.
- When you find it, replace it with the new content using list.set().
Step 3: Write back to the file
Rewrite the file contents by following these steps -
- Write the updated list back to the file using Files.write().
- Surround file operations with a try-catch block to handle exceptions.
Example
Following is the program to overwrite a line in a .txt file using the Files.readAllLines() and Files.write() methods:
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class ReplaceLine { public static void main(String[] args) { // Define the path to the file Path filePath = Paths.get("D://input.txt"); // Line to be replaced and the new line String oldLine = "No preconditions and no impediments. Simply Easy Learning!"; String newLine = "Enjoy the free content"; try { // Read all lines into a list List<String> lines = Files.readAllLines(filePath); // Replace the target line for (int i = 0; i < lines.size(); i++) { if (lines.get(i).equals(oldLine)) { lines.set(i, newLine); } } // Write updated lines back to the file Files.write(filePath, lines); System.out.println("Line replaced successfully."); } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } } }
Following is the output of the above program -
Line replaced successfully. Contents of the file: Welcome to Tutorials Point. No preconditions and no impediments. Simply Easy Learning! This is an example file.