I have a simple single Java file, that has main method and a bunch of other methods. I’d like to open a text file in my main method but keep it open and append to it in my other methods in my java code. what is the best way of doing it in Java.
Share
Take a look at the FileWriter Class in java.io.
The filepath is the name of your file, true is to append and not rewrite your file everytime. This writer would stay open until you close it.
I will point out that this is probably not the best option. Since you can append at anytime to a file, there is no reason to leave your stream open. You can simply recreate it with the append variable as true.
A write method might fit you better, so that you can also put it on it’s own thread some day.