------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------
PrintStream 为其他输出流添加了功能,使它们能够方便地打印各种数据值表示形式。它还提供其他两项功能。与其他输出流不同,PrintStream 永远不会抛出 IOException;而是,异常情况仅设置可通过 checkError 方法测试的内部标志。另外,为了自动刷新,可以创建一个 PrintStream;这意味着可在写入 byte 数组之后自动调用 flush 方法,可调用其中一个 println 方法,或写入一个换行符或字节 ('\n')。PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。
PrintStream 的构造方法 :
PrintStream(File file)
创建具有指定文件且不带自动行刷新的新打印流。
PrintStream(File file, String csn)
创建具有指定文件名称和字符集且不带自动行刷新的新打印流。
PrintStream(OutputStream out)
创建新的打印流。
PrintStream(OutputStream out, boolean autoFlush)
创建新的打印流。
PrintStream(OutputStream out, boolean autoFlush, String encoding)
创建新的打印流。
PrintStream(String fileName)
创建具有指定文件名称且不带自动行刷新的新打印流。
PrintStream(String fileName, String csn)
创建具有指定文件名称和字符集且不带自动行刷新的新打印流。
package com.itheima.bbs.blog_2;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class blog_2 {
/**
* @param args
*/
public static void main(String[] args)throws IOException {
// TODO Auto-generated method stub
try{
int[] a={0,1,2};
System.out.println(a[-1]);//此处有异常
}
catch(Exception e){
try{
PrintStream ps=new PrintStream("ExceptionLog.log");//创建日志文件
Date d=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期模版
String s=sdf.format(d);//改变日期显示格式
ps.println(s);//打印异常日期
System.setOut(ps);//改变标准输出流
}
catch(IOException e1){
throw new RuntimeException("日志文件创建失败!");
}
e.printStackTrace(System.out);//打印异常信息
}
}
}