Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Multiple threads writing to one file

807591Dec 3 2007 — edited Apr 26 2008
Hi There,

I have a program that uses a number of threads, all trying to write to the same text file.
I am using
static BufferedWriter bw = new BufferedWriter(new FileWriter("c:\\temp\\mem.log"));
to write to mem.log file

The problem is that each thread is closing the stream, i.e. it calls:
bw.flush(); 
bw.close();
and when the next thread is trying to write to the same file, using the same bw object, the following exception is thrown:
java.io.IOException: Stream closed
	at java.io.BufferedWriter.ensureOpen(BufferedWriter.java(Inlined Compiled Code))
	at java.io.BufferedWriter.write(BufferedWriter.java(Compiled Code))
	at java.io.Writer.write(Writer.java(Compiled Code))
	at g.out.Game.writeMemoryToLog(Game.java:87)
	at g.out.Start.run(Start.java:59)
	at java.lang.Thread.run(Thread.java:568)
Does anyone know of a way to close the stream after the last thread has written to the file?

Thanks.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 24 2008
Added on Dec 3 2007
9 comments
1,509 views