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 }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM