i’ve a Java program that print out some text output. Actually my simple PrintOutput function is something like
System.out.println("some output");
But i would like to declare a variable
printonfile = true
to print my output to a text file if setted to true, or to screen (console) if setted to false.
How can i assign the out to a file instead to System.out avoiding to make something like
if (printonfile) {
myfile.out("some output");
}
else {
System.out.println("some output");
}
Is there a way to declare an “output” variable at the beginning of my function so i can assign it the standard output (console) or a text file ?
Thanks
The
outfield of the System class is an instance of thePrintStreamclass; you can also construct a PrintStream object that outputs to a file. So your idea of setting up the output location could work as follows