setIn(InputStream) 用于重定向输入源,默认为用户直接输入,即System.in这段代码的运行效果,可将其默认改为从某文件读取数据等;
setOut(PrintStream) 用于重定向输出位置,默认为输出至控制台,即System.out.println的运行效果,可将其默认改为输出至某个文件等;
setErr(PrintStream) 用于重定向错误信息的输出位置,默认也为输出至控制台,即System.err.println的运行效果,可将其默认改为输出至某个文件等;
public class Redirecting { public static void main(String[] args) throws Exception { BufferedInputStream in = new BufferedInputStream(new FileInputStream( "out111.txt")); PrintStream out = new PrintStream(new BufferedOutputStream( new FileOutputStream("test12191419.data"))); //将标准输入源改为从文件out111.txt读取 System.setIn(in); //将标准输出改为写入文件test12191419.data System.setOut(out); //将标准错误输出改为写入文件test12191419.data System.setErr(out); //此时System.in不再是由用户输入数据,而是直接从文件out111.txt读取数据 BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s; while((s=br.readLine())!=null) //此时的输出数据,不是直接打印到屏幕,而是写入文件test12191419.data中 System.out.println(s); out.close(); } }