System.out/in/err重定向实例浅析

来源:互联网 发布:用excel做统计图的数据 编辑:程序博客网 时间:2024/05/22 02:50
import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintStream;public class Main06 {public static void main(String[] args) {InputStream input = System.in;//从键盘接收数据OutputStream out = System.out;//此刻的输出流是向屏幕上输出//大概能感受到OutputStream是级别很高的父类了吧,这就是对象多态性的体现//使用System.out输出是输出到屏幕(显示器)byte b[] = new byte[1024];System.out.print("please input content:");try {int len = input.read(b);out.write(new String(b,0,len).getBytes());//输出重定向System.setOut(new PrintStream(new FileOutputStream(new File("src//JavaIO//test.txt"),true)));System.out.println(new String(b,0,len));input.close();} catch (IOException e) {e.printStackTrace();}//实用案例:打印错误日志String str = "hello";try{System.out.println(Integer.parseInt(str));}catch(Exception e){try{System.setOut(new PrintStream(new FileOutputStream(new File("src//JavaIO//err.log"))));}catch(Exception e1){}System.out.println(e);}//System.err重定向,不建议也不常使用ByteArrayOutputStream baos = new ByteArrayOutputStream();System.setErr(new PrintStream(baos));System.err.print("www.baidu.com");System.err.println("DLMU");System.out.println(baos);/*try{System.out.println(Integer.parseInt("hello"));}catch(Exception e){//System.err表示的是错误的标准输出,程序出现错误,直接使用System.err进行打印System.err.println(e);//e.printStackTrace(s);}*/}}

System.out与System.err相信大家一看上面的实例就明白了,至于System.in就不在代码块中写了,都差不多

System.setIn(new FileInputStream("xxx.xxx"));InputStream input = System.in;byte[] b = new byte[1024];int len = input.read(b);System.out.println(new String(b,0,len));input.close();







原创粉丝点击