错误信息和输出信息写到文件

作者在 2010-05-21 15:38:11 发布以下内容
import java.io.*;
import java.util.Date;

public class TestSetOutput{
    public static void main(String[] args){
        PrintStream ps = null;
        PrintStream ps_error = null;
        try{
            ps = new PrintStream(new FileOutputStream("output.txt",true));
            System.setOut(ps);//设置他的输出流形式,如果没有参数则写到控制台
//写了之后,将写到这个输出文件中
            ps_error = new PrintStream(new FileOutputStream("errorLog.txt",true));
            System.setErr(ps_error);//设置错误输出形式,

            int avg = 0;
            int total = 0;
            int count = 0;
            int num = 0;
            int i;
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String s = br.readLine();
            while(s != null && !s.equals("over")){
                i = Integer.parseInt(s);
                num++;
                total += i;
                avg = total/num;
                System.out.println("num=" + num + "\ttotal=" + total + "\tavg=" + avg);    
                s = br.readLine();
            }
        }catch(Exception e){
            System.err.println("出错时间: " + new Date());
            System.err.print("错误信息:");//这里的err表示错误的输出行式
            e.printStackTrace(System.err);    
        }finally{
            try{
                ps.close();
                ps_error.close();
            }catch(Exception e1){
                System.err.println("出错时间: " + new Date());
                System.err.print("错误信息:");
                e1.printStackTrace(System.err);    
            }    
        }
    }
}
I/O编 | 阅读 998 次
文章评论,共0条
游客请输入验证码
浏览275915次