Java的标准输入/输出分别通过System.in和System.out来代表,在默认的情况下分别代表键盘和显示器,当程序通过System.in来获得输入时,实际上是通过键盘获得输入。当程序通过System.out执行输出时,程序总是输出到屏幕。
在System类中提供了三个重定向标准输入/输出的方法
static void setErr(PrintStream err) 重定向“标准”错误输出流
static void setIn(InputStream in) 重定向“标准”输入流
static void setOut(PrintStream out)重定向“标准”输出流
package com.test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("input.txt");
System.setIn(fis);
Scanner sc = new Scanner(System.in);
/*
可以开始从input.txt文件中读入数据
*/
PrintStream ps = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(ps);
/*
输出结果到output.txt文件中
*/
}
}