重定向输出流实现程序日志输出
System类中的out成员变量是JAVA的标准输出流,out成员变量被定义为final型,无法直接复制,但可以通过setOut方法来设置新的输出流,同理,err和in也可通过setErr()和setIn()来实现重定向功能。
1 public static void main(String[] args){ 2 try { 3 PrintStream out = System.out; // save previous outStream 4 PrintStream ps = new PrintStream("./log.txt"); //create fileOutStream 5 System.setOut(ps); //重定向输出流 6 int age = 20; 7 String name = "tom"; 8 System.out.println("the age is:"+age); 9 System.out.println("the name is:"+name); 10 System.setOut(out); 11 System.out.println("Please look up the log"); 12 }catch (Exception e){ 13 e.printStackTrace(); 14 } 15 }