java基础51 IO流技术(打印流)

1、打印流(printStream)的概念

    打印流可以打印任意的数据类型

2、printStream的步骤

    1.找到目标文件
    2.创建一个打印流
    3.打印信息
    4.关闭资源

3、实例

 1 package com.dhb.file;
 2 
 3 import java.io.File;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.PrintStream;
 7 
 8 /**
 9  * @author DSHORE / 2018-7-19
10  *
11  */
12 /* 打印流(printStream):打印流可以打印任意的数据类型
13  * */
14 class Animal{
15     String name;
16     String color;
17     public Animal(String name, String color) {
18         super();
19         this.name = name;
20         this.color = color;
21     }
22     @Override
23     public String toString() {
24         return "Animal [name=" + name + ", color=" + color + "]";
25     }
26 }
27 
28 public class Demo25 {
29     public static void main(String[] args) throws IOException {
30         //找到目标文件
31         File file = new File("F:\\e.txt");
32         //创建一个打印流
33         PrintStream ps = new PrintStream(file);
34         //打印信息
35         ps.println(97);
36         ps.println(3.14);
37         Animal a = new Animal("二狗子", "咖啡色");
38         ps.println(a);
39         ps.println('a');
40         
41         System.setOut(ps);//重新设置标准打印流对象
42         System.out.println("hello,哈罗!");
43         
44         //收集异常日志信息
45         File logFile=new File("F:\\2018年7月19日.log");
46         PrintStream logPrintStream=new PrintStream(new FileOutputStream(logFile),true);
47         for (int i = 0; i <10; i++) {
48             try {
49                 int c=4/0;
50             } catch (Exception e) {
51                 e.printStackTrace(logPrintStream);//打印到logPrintStream对象中,即:2016年9月3日.log文件上
52             }
53         }
54         //关闭资源
55         ps.close();
56     }
57 }

运行结果图

      

 

 

 

 

 

原创作者:DSHORE

作者主页:http://www.cnblogs.com/dshore123/

原文出自:https://www.cnblogs.com/dshore123/p/9337069.html

欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!

posted @ 2018-07-19 17:23  DSHORE  阅读(270)  评论(0编辑  收藏  举报