Use case:
When an output file is defined, message will be printed to file, otherwise message will be printed to stdout.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
public class TestMain {
public static void main(String[] args) {
TestMain m = new TestMain();
PrintStream ps = m.getPrintStream("/tmp/a.txt");
ps.print("Hello World!");
}
/**
* Print message to file identified by filename,
* or stdout if filename is not provided.
*
* @param filename
* @return
*/
@SuppressWarnings("resource")
public PrintStream getPrintStream (String filename) {
OutputStream os = null;
try {
os = new FileOutputStream(filename);
} catch (FileNotFoundException e1) {
os = System.out;
}
PrintStream ps = new PrintStream(os);
return ps;
}
}