Output message to a file or stdout

来源:互联网 发布:淘宝hd版怎样改电脑版 编辑:程序博客网 时间:2024/05/20 22:31


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; }}


0 0