I'm a bit stuck right now. I'm going to have a program that will be taking dynamically created Strings (in the case of this test, the input taken from a BufferedReader using readLine()), and write them to a text file. It's essentially a log. The simplest way to do this would probably be to have a static FileWriter and pass the String to a method that would write it to a text file and then close the connection. This would be easy, but it seems inefficient because you would have to write and close for every String. My first idea was to have a separate thread that would do the writing so it wouldn't have to close the connection all the time. The trouble is that I can't figure out how it is possible to pass each String to the method that is writing to the file. Or am I on the wrong track entirely? I feel like this should be basic, but I just can't seem to figure it out . All help is appreciated!
P.S. I put this in the "I/O and Streams" forum, but I wasn't sure if it should go in the "Threads and Synchronization" forum. I figured it should go here considering that the solution may or may not revolve around threading.
I think you're making that way more complicated than it actually is. Yes, it is basic (as you put it). Here's what you need to do for writing a log:
(1) Open the file at the start of the program.
(2) Write log records whenever you need to write them.
(3) Close the file at the end of the program.
I don't know where you got the idea that you need to keep closing the file. Don't close it until you've finished writing to it. And I don't know where you got the idea that you need threads to do those three simple things. You don't. It could hardly be simpler.
posted 8 years ago
Wow, I feel silly. I tend to overthink things, as I'm sure you noticed. I'm coming back to programming after a very long hiatus, so I'm rusty, on both the language itself (syntax, etc) and also general design and logic. I feel stupid... Anyway, I created a static BufferedWriter, instantiated it in a method that I'm using to set things up for the bulk of the program and then closed it right before the program ends. Paul, I'm sorry that I made you answer a pretty obvious question. But now I know that, when faced with a challenge, I need to step back and find the simplest and most efficient way to solve a problem. Thank you for pointing me in the right direction!