标准的字节输出流 & 如何用它写一篇日志文件

java.io.printStream

标准的字节输出流。默认输出到控制台

    public static void main(String[] args) throws Exception {
        //联合起来写
        System.out.println("hello world");

        //分开写
        PrintStream ps = System.out;
        ps.println("hello zhangsan");
        ps.println("hello lisi");
        ps.println("hello wangwu");

        //标准输出流不需要捕获异常 不需要手动close()关闭
        /*
        之前学习过的方法和属性
        System.gc()
        System.currentTimeMills();
        PrintStream ps = System.out;
        System.exit();
        System.arraycopy()
         */

        //改变标准输出流的输出方向
        //标准输出流不再指向控制台,指向log文件
        PrintStream printStream = new PrintStream(new FileOutputStream("log.txt"));
        //修改输出方向,将输出方向修改到log文件
        System.setOut(printStream);
        // 再输出
        System.out.println("hello world");
        System.out.println("hello kitty");
        System.out.println("hello zhangsan");
    }
日志文件
public class Logger {
    public static void log(String msg){
        try {
            PrintStream printStream = new PrintStream(new FileOutputStream(
                    "log.txt",true));
            System.setOut(printStream);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
            String format = sdf.format(date);
            System.out.println(format + ":" + msg);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
public class LogApplication {
    public static void main(String[] args) {
        Logger.log("调用了System.gc()方法");
        Logger.log("不想打代码");
        Logger.log("烦死了");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值