重定向标准输出

各位看官,今天我们来聊聊标准IO流的重定向问题。必须,在编程时会输出大量信息到屏幕上,非常不方便阅读,我们可以通过对于标准输出的重定向,从而使得阅读更方便。主要涉及的方法为:setIn(InputStream),setOut(PrintStream),setErr(PrintStream).
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();
	}
}

猜你喜欢

转载自karenit.iteye.com/blog/2346103