java重定向stderror,重定向stderror,要重定向stderror
分享于 点击 48413 次 点评:79
java重定向stderror,重定向stderror,要重定向stderror
要重定向stderror需要调用System的setErr()方法,该方法接受一个PrintStream对象作为参数。
下面的示例代码创建了一个基于文件的FileOutputStream将stderror的内容保存到一个文件中。
import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.PrintStream;/** * Main.java * * @author byrx.net */public class Main { /** * Redirects System.err and sends all data to a file. * */ public void redirectSystemErr() { try { System.setErr(new PrintStream(new FileOutputStream("system_err.txt"))); String nullString = null; //Forcing an exception to have the stacktrace printed on System.err nullString = nullString.toUpperCase(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } } /** * Starts the program * * @param args the command line arguments */ public static void main(String[] args) { new Main().redirectSystemErr(); }}
用户点评