使用System.setOut(PrintStream流);影響范圍是設定后的區域,設定后的區域即便是其他類中的方法也會重定向。
1 package setout; 2 3 public class OtherDemo { 4 public static void meth(){ 5 System.out.println("text"); 6 } 7 }
1 package setout; 2 3 import java.io.FileNotFoundException; 4 import java.io.FileOutputStream; 5 import java.io.PrintStream; 6 7 public class SetOutDemo { 8 public static void main(String[] args) { 9 try(PrintStream p = new PrintStream(new FileOutputStream("src//setout//abc.txt"))){ 10 System.out.println("qian"); 11 System.setOut(p); 12 /** 13 * 其他類中的syso語句也重定向了 14 * 15 * 輸出結果 16 * "C:\Program Files\Java\jdk1.8.0_131\bin\java.exe" ... 17 * qian 18 * 19 * Process finished with exit code 0 20 */ 21 System.out.println("hou"); 22 OtherDemo.meth(); 23 } catch (FileNotFoundException e) { 24 e.printStackTrace(); 25 } 26 } 27 }
abc.txt文本內容
hou
text