mattias wrote:
>
> Here's the code, it hangs while executing the very first line of code:
>
> FileWriter fileWriter = new FileWriter("log.txt", true);
> BufferedWriter buffWriter = new BufferedWriter(fileWriter);
> buffWriter.write(message);
> buffWriter.newLine();
> buffWriter.close();
As jan says, looks like a dead lock. However the code isn't safe as you
don't guarantee to close the FileWriter. It should look something like:
FileWriter fileWriter = new FileWriter("log.txt", true);
try {
BufferedWriter buffWriter = new BufferedWriter(fileWriter);
buffWriter.write(message);
buffWriter.newLine();
buffWriter.close();
} finally {
fileWriter.close();
}
In any case opening and closing a file that fast doesn't seem like a
good idea. It's heavy on operating system resources and also on
finalisers. If multiple processes do need to access the single file,
then you are quite likely to have lots of exceptions as they collide.
If it is true that multiple processes need to access the file, perhaps a
better route is to use RandomAccessFile. From that you can get the
java.nio.channels.FileChannel which allows locking and unlocking
exclusive access to the file without opening and closing. I must admit
that I have not tried that myself.
Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/