printStream(打印流)

打印流(printStream)  打印流可以打印任意类型的数据,而且打印数据之前都会先把数据转换成字符串再进行打印。
 使用:
 1.把错误日志信息打印在一个文件中记录下来
   e.printStackTrace():默认打印在控制台
   e.printStackTrace(PrintStream s):打印到PrintStream流中保存在对应的文件里
         为了让信息不覆盖,在创建printStream的时候需要传递PrintStream(OutputStream out)参数,添加true属性
 
 2.设置打印在控制台的信息打印到其他地方:

   System.setOut(logPrintStream);

class Animal{
	
	String name;
	
	String color;
	
	public Animal(String name,String color){
		this.name = name;
		this.color = color;
	}
	
	@Override
	public String toString() {
		return "名字:"+this.name+ " 颜色:"+ this.color;
	}
	
}



public class Demo6 {
	
	public static void main(String[] args) throws IOException {
		/*FileOutputStream fileOutputStream = new FileOutputStream("F:\\a.txt");
		fileOutputStream.write("97".getBytes());
		fileOutputStream.close();*/
		
		
		//打印流可以打印任何类型的数据,而且打印数据之前都会先把数据转换成字符串再进行打印。
		File file = new  File("F:\\a.txt");
		//创建一个打印流
		PrintStream printStream = new PrintStream(file);
		/*
		printStream.println(97);
		printStream.println(3.14);
		printStream.println('a');
		printStream.println(true);
		Animal a = new Animal("老鼠", "黑色");
		printStream.println(a);
		
		
		//默认标准的输出流就是向控制台输出的,
		System.setOut(printStream); //重新设置了标准的输出流对象
		System.out.println("哈哈,猜猜我在哪里!!");
		*/
		
		//收集异常的日志信息。
		File logFile = new File("E:\\2015年1月8日.log");
		PrintStream logPrintStream = new PrintStream( new FileOutputStream(logFile,true) );
		try{
			int c = 4/0;
			System.out.println("c="+c);
			int[] arr = null;
			System.out.println(arr.length);
			
		}catch(Exception e){
			e.printStackTrace(logPrintStream);
			
			
		}
		
		
		
	}

}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值