Reputation: 10964
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.
Upvotes: 1
Views: 962
Reputation: 199244
You need what in object oriented programming is called an "Instance variable"
This variable is accessible from methods in the same object and you don't have to pass it around.
So your class could be defined as:
class MyClass {
// This is your instance variable
private PrintWriter output;
public void methodOne() {
output.println("One");
}
public void methodTwo() {
output.println("Two");
}
public void methodThree() {
output.println("Three");
}
// you get the idea
public void close(){
output.close();
}
}
That way you can create an object of MyClass
and initialize your instance variable and use it in all the methods.
This could be the main method:
public static void main( String [] args ) {
MyClass object = new MyClass();
// add another method to initialize the instance variable
object.useFile("/Users/yourname/yourFile.txt");
// useFile defined as: internally initialized as:
// output = new PrintStream( new FileOutputStream( fileName ));
object.methodOne();
object.methodTwo();
object.methodThree(),
object.close();
}
The idea, is to have a private attribute which is used in the rest of the methods, so you don't have to pass the reference all over the place.
If you have different classes trying to access the same attribute, maybe you could move those methods to this class.
Upvotes: 2
Reputation: 7278
Take a look at the FileWriter Class in java.io.
private FileWriter _writer;
public static void main(String args[])
{
_writer = new FileWriter(filePath, true);
}
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.
_writer.close();
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.
public static void write(String output)
{
FileWriter writer = new FileWriter(filePath, true);
writer.write(output);
writer.close();
}
Upvotes: 3
Reputation: 89749
What you are seeking is a Writer, an object that lets methods write into it (or PrintWriter, which lets you print line-by-line). You can create Writers from various output sources, including files with FileWriter.
Upvotes: 1