Java学习之System的setOut方法重定向影响范围

使用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

posted @ 2020-10-26 19:39  康舒服冰红茶  阅读(910)  评论(0编辑  收藏  举报