java入门 -- 打印流PintStream

/*

* 打印流PrintStream

* 作用:

* 1.可以打印任何类的数据,打印数据之前都会先把数据转换成字符串再进行打印;

* 2.收集异常的日志信息;

*

* 说明:默认标准输出流就是向控制台输出的,的System中的out就是一个PrintStream类对象,可以通过setOut来重新定义输入的位置

*

*/

package com.michael.lin;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.PrintStream;

class User{

String name;

String sex;

public User(String name, String sex){

this.name = name;

this.sex = sex;

}

public String toString(){

return "姓名"+this.name + this.sex +"性别";

}

}

public class Demo6 {

public static void main(String[] args) throws FileNotFoundException{

//1.定位文件

File file = new File("c:\\a.txt");

//2.声明打印流

PrintStream printStream = new PrintStream(file);

//1.作用1:打印任何类型的数据

/*User user = new User("金哥","男");

printStream.print(user);

printStream.print(97);

printStream.print(true);*/

//重新设置标准的输出流对象.类似于输出重定向

System.setOut(printStream);

System.out.println("你好啊");

//2.收集错误信息并打印到日志

File file1 = new File("c:\\log.txt");

//PrintStream printStream1 = new PrintStream(file1); 每次写入都会清空

//以写入的方式打印到日志文件

PrintStream printStream1 = new PrintStream(new FileOutputStream(file1,true));

while(true){

try{

int a = 4/0;

}catch(Exception e){

e.printStackTrace(printStream1);

}

}

}

}

你可能感兴趣的:(java入门 -- 打印流PintStream)