my dog learned polymorphism*
The moose likes Sockets and Internet Protocols and the fly likes Remove Line from Text File Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "Remove Line from Text File" Watch "Remove Line from Text File" New topic
Author

Remove Line from Text File

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
We are writing certain lines in a text file ,after a period of time we want to remove those lines from the text file.
For reading file
FileReader fr=new FileReader("time.txt");
BufferedReader br=new BufferedReader(fr);
while((read=br.readLine())!=null )
{
}
For writing file
FileWriter f0=new FileWriter("Clientdata1.txt",true);
f0.write(data);
f0.close();
NOW MY DIFFICULTY IS HOW TO REMOVE LINES FROM A TEXT FILE.
ppathak
Greenhorn

Joined: Jul 06, 2000
Posts: 19
Hi !!
From the way i understand u'r question, i think u r reading frm one file but writing into a different file , right!
i am assuming u have some function which evaluates which line is to be removed & returns true / false. if return value is false then write to file
basically the code will be some thing of this sort
FileReader fr=new FileReader("time.txt");
BufferedReader br=new BufferedReader(fr);
boolean b;
while((str=br.readLine())!=null )
{
b = evaluate(str);// evaluate is a function which determies
// whether line has to be removed or not
if (b==false)
{
// code for appending
}

}
there are many other ways of doing the above.
i hope i am clear
cheers,
Preeti Pathak
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Sorry for putting question in wrong way. I am reading and writing information in the same file.
Now i want to remove some line from text file. BUT HOW ???
Hope this time i am clear...
ppathak
Greenhorn

Joined: Jul 06, 2000
Posts: 19
As of now i cn think of 2 ways:
*
If u r reading & wish to write back to same file then i would suggest, u concatenate all the lines which u need in a StringBuffer & then once u r done with reading the file, close it & open it in write mode & write stringbuffer to it.
PS: take care for \n
* write all the lines u need in a temp file , then copy the contents back to the old file
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Remove Line from Text File