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

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

示例代码如下:

 package redirect;

 import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Scanner; public class Main {
public static void main(String[] args) throws FileNotFoundException {
/**
* 保存最原始的输入输出流
*/
InputStream in = System.in;
PrintStream out = System.out;
/**
* 将标准输入流重定向至 in.txt
*/
System.setIn(new FileInputStream("in.txt")); Scanner scanner = new Scanner(System.in);
/**
* 将标准输出流重定向至 out.txt
*/
System.setOut(new PrintStream("out.txt"));
/**
* 将 in.txt中的数据输出到 out.txt中
*/
while (scanner.hasNextLine()) {
String str = scanner.nextLine();
System.out.println(str);
}
/**
* 将标准输出流重定向至控制台
*/
System.setIn(in);
/**
* 将标准输出流重定向至控制台
*/
System.setOut(out);
scanner = new Scanner(System.in);
String string = scanner.nextLine();
System.out.println("输入输出流已经恢复 " + string);
}
}
上一篇:oracle 之 包,包体创建和使用案例


下一篇:小小C程序(九九乘法表)