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;
}
}
本文介绍了一个简单的Java程序,该程序可以根据提供的文件名将消息打印到指定文件或默认的标准输出。通过使用`PrintStream`类和条件判断,实现了灵活的消息输出方式。
717

被折叠的 条评论
为什么被折叠?



