aspose file tools
The moose likes Beginning Java and the fly likes How to append my text data to a file Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "How to append my text data to a file" Watch "How to append my text data to a file" New topic
Author

How to append my text data to a file

surendar prabu
Ranch Hand

Joined: Jul 24, 2006
Posts: 102
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


SCJP 1.4
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
make the FileWriter object in A, static
you'll probably also need a static method to close the file
shan sundaram
Greenhorn

Joined: Feb 07, 2004
Posts: 15
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

Joined: Oct 20, 2005
Posts: 257

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

Joined: Jul 11, 2001
Posts: 14112
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.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: How to append my text data to a file
 
Similar Threads
Line Feed Carriage Return problem
StringBuffer
== operator....
Which one to choose (JDK 1.3 - JDK 1.4)
p6spy - spy.properties settings