Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Remove Line from Text File

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic