Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to append my text data to a file  RSS feed

 
surendar prabu
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a class A which uses FileWriter to write in to a NotePad file.

And i have class B and class C, both creates object of class A and try to write onto the same file at same time. But only one class either class B or class C is writing into the file.
But i need both the classes to write in to the file. Like i need to append to the contents of the file continuosly. you may consider like i am trying to write a log file for my application.

Help me out.
regards,
Surendar
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
make the FileWriter object in A, static
you'll probably also need a static method to close the file
 
shan sundaram
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi You can try to have the following constructor method.

FileWriter fw = new FileWriter(file,true);

The boolean value true will append end of the file.
 
Srinivas Kalvala
Ranch Hand
Posts: 257
Firefox Browser Hibernate Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Make the Class A as singleton pattern, that is making single global instance for any access.

So Class B and Class C can write into the file at a time but in sequence.

Static will be used to make singleton in java.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
B and C need to use the same instance of A. Making A a singleton would be one solution, but not my preferred one.

You will likely also need to synchronize A properly.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!