• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem writing a string to a file(Urgent)

 
rudolf hitler
Ranch Hand
Posts: 34
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how do i write a string to a file.I have tried the following but it doesnt seem to work .Can you let me now what the problem might be.
File f=new File("archive.txt");
FileWriter fw=new FileWriter(f,true);
BufferedWriter bw=new BufferedWriter(fw);
String a="aaaaa";
bw.write(a);
I tried this once it worked but when i ran my program a second time it just opens the file archive.txt but does not write anythin into it.
I tried converting the string into an array of characters and then writing it only using file writer but it didnt seem to work even then.
What might the problem be?
 
Hari Gangadharan
Ranch Hand
Posts: 73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Flush it after you use it

I mean you need to do:

Hope this helps.
 
rudolf hitler
Ranch Hand
Posts: 34
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanx a lot for the help but can u explain how come it worked when i ran it the first time and then stopped workin if it is coz of the flush problem
 
Hari Gangadharan
Ranch Hand
Posts: 73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java ensures that the files are closed on exit. In the current case the BufferedWriter wraps your FileWriter. BufferedWriter's default behaviour is to flush the buffer to file once in a while. So if you are using a buffered file writer and if you do not explicitly call flush then there is chance that some of the stuff written is not physically written to disk. You can experience this when you are writing huge files (the last chunk may be missing). So I would assume that the first time it happened because the buffered writer flush executed before the file writer is closed.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic