1.效果图
1.1 Console
1.2 log.txt
2.Java代码
main()方法
public static void main(String[] args) {
//21 将调试信息和错误信息保存到指定的日志文件中
printMsg2Log("我是调试信息", "我是错误信息", "F:\\lee\\test\\log.txt");
}
printMsg2Log()方法
/**
* @Title: printMsg2Log
* @Description: 将调试信息和错误信息保存到指定的日志文件中
* @param debugmsg2
* @param errormsg2
* @author 大都督
* @date 2019年1月14日
* @return void
*/
public static void printMsg2Log(String debugMsg, String errorMsg, String fileName) {
//标准输出流
PrintStream out = System.out;
//标准错误输出流
PrintStream err = System.err;
//文件输出流
try {
PrintStream printStream = new PrintStream(fileName);
//将调试信息重定向到文件输出流中
System.setOut(printStream);
System.out.println(debugMsg);
//将错误信息重定向到文件输出流中
System.setErr(printStream);
System.err.println("warning:"+errorMsg);
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
}finally {
System.setOut(out);
System.out.println("程序运行完毕,请查看"+fileName+"日志文件");
out.close();
err.close();
}
}