How to delete a string inside a file(.txt) in java?



In this article, we will learn how to delete a string inside a file (.txt) in Java. The following are the ways to do so:

Using FileOutputStream

The FileOutputStream is a class in the java.io package. It is mainly used for writing data to a file. It creates a file output stream to write data to the specified file.

To delete a string inside a file using the FileOutputStream class, follow the steps below:

  • Create a file object using the File class.
  • Read the file content as a string using Files class.
  • Remove the string you don't want by using replace() method.
  • Write the new content back to the file using FileOutputStream.

Example

Let's say we have a file named sample.txt with the following content:

This is a sample file.
This file is used for testing purposes.

Following is the Java program to delete a string inside a file using the FileOutputStream class:

import java.io.*
import java.nio.file.*

public class DeleteStringFromFile {
   public static void main(String[] args) throws IOException {
      File file = new File("D:\sample.txt")
      String content = new String(Files.readAllBytes(file.toPath()))
      content = content.replace("sample", "")
      FileOutputStream fos = new FileOutputStream(file)
      fos.write(content.getBytes())
      fos.close()
      System.out.println("String deleted successfully.")
   }
}

Output

Following is the output of the above code:

String deleted successfully.

Now, if we open the sample.txt file, we will see the following content:

This is a  file.
This file is used for testing purposes.

Using replace() method

We can also use the replace() method of the String class to delete a string inside a file.

In this method, we will read the file content as a string and then use the replace() method to remove the string we don't want.

Finally, we will write the new content back to the file.

Example

Following is the Java program to delete a string inside a file using the replace() method:

import java.io.*
import java.nio.file.*

public class DeleteStringFromFile {
   public static void main(String[] args) throws IOException {
      File file = new File("D:\sample.txt")
      String content = new String(Files.readAllBytes(file.toPath()))
      content = content.replace("sample", "")
      Files.write(file.toPath(), content.getBytes())
      System.out.println("String deleted successfully.")
   }
}

Output

Following is the output of the above code:

String deleted successfully.

Now, if we open the sample.txt file, we will see the following content:

This is a  file.
This file is used for testing purposes.
Aishwarya Naglot
Aishwarya Naglot

Writing clean code… when the bugs aren’t looking.

Updated on: 2025-09-01T13:59:21+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements