Click here to Skip to main content
15,896,111 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a text("Rachel") and i want to search for that user in that file and if found then actually delete the record of Rachel. Now, i tried something but for some reason the code is no deleting the user Rachel. Can anyone please help me out? Thanks


Java
import java.io.*;     
import java.util.*; 

public class trial {
	public static void main(String args[]) throws IOException
	{
		 FileReader fr = new FileReader("Textsave.txt");     
		 BufferedReader br = new BufferedReader(fr);   
		 String line = null;
		 String delete = "Rachel";
		 while((line = br.readLine()) != null)
		 {
			 if(line.contains(delete))
			 {
				 System.out.println("Found");
				 System.out.println(line);

				 line.replace(delete, "");
				 
			 }
		 }
		 
		 
		 br.close();
		 
	}

}
Posted

very few times in an o/s and/or programming language, do I see the ability to simply delete a line from a file

usually, what you do (depending on the size of the file) is read the lines, manipulate them (including 'skip' the ones you don't want to replace, ie delete, and write them out to a(nother) file - its sometimes easier to write them out to a temporary file until your finished, then delete the original file and rename the temporary one to the file you're supposed to have (its safer, if anything goes wrong you still have a copy of the data)

in your case, you could read from a file like you have, but create a FileWriter and write to "Textsave.Txt.Tmp", that is, you write all lines to the '.Tmp' version except the line(s) you have identified as needing to be removed
 
Share this answer
 
The first thing i would like to highlight in above program, file is opened in Read Mode, this will not allow user to modify the file.

To achieve the same you can use RandomAccessFile , but it is part of Java 7
http://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html


Still the ideal solution will be given by Mr. Garth. Instead of over-writing the existing file it is always good copy the required contents in one temp file , delete the existing file, and then rename the temp file to original file.
Regards,
panduranga.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900