1、1.建立模型:在java文件编辑界面中,输入一下代码来重定向输出流,由于输出流会抛出一个异常,所有就采用了try--catch--结构;public static void main(String[] args) { try{ PrintStream mytxt=new PrintStream("./log.txt"); }catch(FileNotFoundException e){ e.printStackTrace(); } }
2、2.重定向println();输入第一条指令对原有的输出流方向进行缓存,接着采用system中的setout方法进行重定向;代码如下:PrintStream out=System.out; System.setOut(mytxt);
3、3.保存日记:采用Date方法对日期进行读取,读取后保存到文件中,该命令与我们常规的输出指令一致;System.out.println("文档执行的日期是:"+new Date());
4、4.界面打印:为了显示重定向的效果,本例将输出重定位到原来情况; System.setOut(out); System.out.println("日期保存完毕。");
5、5:总体代码:为了便于大家的理解,将这个main方法的整个代码进行粘贴了下来; public static void main(String[] args) { try{ PrintStream mytxt=new PrintStream("./log.txt"); PrintStream out=System.out; System.setOut(mytxt); System.out.println("文档执行的日期是:"+new Date()); System.setOut(out); System.out.println("日期保存完毕。"); }catch(FileNotFoundException e){ e.printStackTrace(); } }