上代码了解一下:
1 package com.etc; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.FileDescriptor; 6 import java.io.FileInputStream; 7 import java.io.FileNotFoundException; 8 import java.io.FileOutputStream; 9 import java.io.InputStream; 10 import java.io.PrintStream; 11 import java.util.Scanner; 12 13 /* 14 * 对输入输出流进行打印 15 * System.in 16 * System.out 17 * System.err 18 * 输入输出重定向: 19 * System.setIn(InputStream in) 20 * System.setOut(PrintStream out) 21 * System.setErr(PrintStream err); 22 * 回控制台: 23 * FileDescriptor.in 24 * FileDescriptor.out 25 * FileDescriptor.err 26 */ 27 public class OverideSystem { 28 29 public static void main(String[] args) throws FileNotFoundException { 30 31 Overide(); 32 System.out.println("I like codes very much!"); 33 testPrintStream(); 34 console(); 35 System.out.println("hello,控制台"); 36 } 37 //重定向方法实现 38 public static void Overide() throws FileNotFoundException { 39 //重定向输出方式及自动更新 40 System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("E:/test.txt")),true)); 41 } 42 43 public static void testPrintStream() throws FileNotFoundException { 44 //通过文件输入流放入系统的输入,然后再通过Scanner函数将输入结果打印出来 45 InputStream in=System.in; 46 in=new BufferedInputStream(new FileInputStream("E:/test.txt")); 47 Scanner sc=new Scanner(in); 48 System.out.println("输出结果:"); 49 System.out.println(sc.nextLine()); 50 } 51 //返回控制台输出 52 public static void console() { 53 System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)),true)); 54 } 55 }
效果截图:
ps:文章仅作学习了解一用,并未深入,欢迎大佬点评。