Java标准输入输出流的重定向及恢复

       在Java中输入输出数据一般(图形化界面例外)要用到标准输入输出流System.in和System.out,System.in,System.out默认指向控制台,但有时程序从文件中输入数据并将结果输送到文件中,这是就需要用到流的重定向,标准输入流的重定向为System.setIn(InputStream in),标准输出流的重定向为System.setOut(PrintStream out)。若想重定向之后恢复流的原始指向,就需要保存下最原始的标准输入输出流。

示例代码如下:

 

 1 package redirect;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.InputStream;
 6 import java.io.PrintStream;
 7 import java.util.Scanner;
 8 
 9 public class Main {
10     public static void main(String[] args) throws FileNotFoundException {
11         /**
12          * 保存最原始的输入输出流
13          */
14         InputStream in = System.in;
15         PrintStream out = System.out;
16         /**
17          * 将标准输入流重定向至 in.txt
18          */
19         System.setIn(new FileInputStream("in.txt"));
20         
21         Scanner scanner = new Scanner(System.in);
22         /**
23          * 将标准输出流重定向至 out.txt
24          */
25         System.setOut(new PrintStream("out.txt"));
26         /**
27          * 将 in.txt中的数据输出到 out.txt中
28          */
29         while (scanner.hasNextLine()) {
30             String str = scanner.nextLine();
31             System.out.println(str);
32         }
33         /**
34          * 将标准输出流重定向至控制台
35          */
36         System.setIn(in);
37         /**
38          * 将标准输出流重定向至控制台
39          */
40         System.setOut(out);
41         scanner = new Scanner(System.in);
42         String string = scanner.nextLine();
43         System.out.println("输入输出流已经恢复 " + string);
44     }
45 }

 

 

 

posted @ 2014-03-20 18:15  瓦尔登湖畔的小木屋  阅读(4567)  评论(0编辑  收藏  举报