Java program to delete certain text from a file

JavaServer Side ProgrammingProgramming

To delete certain text from a file in Java, let us see the following code snippet −

Example

File input_file = new File("path to the .txt file");
File temp_file = new File("path to the .txt file");
BufferedReader my_reader = new BufferedReader(new FileReader(input_file));
BufferedWriter my_writer = new BufferedWriter(new FileWriter(temp_file));
String lineToRemove = "string to remove";
String current_line;
while((current_line = my_reader.readLine()) != null) {
   String trimmedLine = current_line.trim();
   if(trimmedLine.equals(lineToRemove)) continue;
   my_writer.write(current_line + System.getProperty("line.separator"));
}
my_writer.close();
my_reader.close();
boolean is_success = temp_file.renameTo(input_file);

Output

The input file’s specific string is deleted.

Two files are defined, one being the input file and another one a temporary file. A buffered reader and a buffered writer instances are created, and the string that needs to be removed from the string is defined. The input file is iterated through, and when the string that needs to be deleted is encountered, it is deleted, and the reader and writer instances are closed, and if this operation is successfully, the name of input file is assigned to the temporary file.

raja
Published on 08-Jul-2020 11:47:35
Advertisements