• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about File, FileWriter + BufferedWriter

 
Florin Florentin
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello.

I have a question about working and writing to files. I tried to write to a file using a BufferedWriter, and then use the same BufferedWriter to write to a new file. I've created a new FileWriter object, in which constructor i've passed a new file reference, but that not worked as i was expecting.

Here is the code :



After i'm running this code, there is no text been writed in f2. It's been writed twice in f1.
If i insert this
bw = new BufferedWriter(fw);
on the "//insert code" line, the code will run as i want, but i don't understant why it's not enough to make only fw refering to a new object ?

Is this a String related behavior?
 
Rajeev Rnair
Ranch Hand
Posts: 310
1
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Florin Florentin wrote:Hello.

I have a question about working and writing to files. I tried to write to a file using a BufferedWriter, and then use the same BufferedWriter to write to a new file. I've created a new FileWriter object, in which constructor i've passed a new file reference, but that not worked as i was expecting.

Here is the code :



After i'm running this code, there is no text been writed in f2. It's been writed twice in f1.
If i insert this
bw = new BufferedWriter(fw);
on the "//insert code" line, the code will run as i want, but i don't understant why it's not enough to make only fw refering to a new object ?

Is this a String related behavior?


Just before the // insert code, "bw" is still pointing to the old FileWriter(f1) even though you have re assigned fw= new FileWriter(2);
That means anything you write on "bw" writes to the old file f1.

This is why you have to re assign bw by inserting the "// bw = new BufferedWriter(fw)" to get the text written to File2

 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent clarity of response Rajeev.

Good luck mate,
 
Rajeev Rnair
Ranch Hand
Posts: 310
1
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prithvi Sehgal wrote:Excellent clarity of response Rajeev.

Good luck mate,


thanks Prithvi, good luck to you too
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic