编写自己的日志输出文件

来源:互联网 发布:linux awk 时间函数 编辑:程序博客网 时间:2024/05/01 04:23
import java.io.BufferedReader;import java.io.CharArrayWriter;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintStream;import java.io.PrintWriter;import java.util.Arrays;import java.util.Date;import java.util.List;public class TestClass {public static void main(String[] args) {PrintStream ps = null;PrintStream ps_error = null;try{//设置日志的正确输出流,第二个参数的含义是不是覆盖之前的记录(记录的内容都是最新修改后的内容)//如果设置为false那么日志里面只能够记录最后一次运行的结果,因为它已经把之前的覆盖掉了//所以这个地方肯定要设置为true才行的ps = new PrintStream(new FileOutputStream("output.txt",true));//设置out的输出目的地为ps(把控制台的打印信息写入了文件)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("错误信息:");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);}}}}