JAVA-----IO篇六(标准输出流PrintStream以及简易日志实现)

JAVA-----IO篇六(标准输出流PrintStream以及简易日志实现)

PrintStream

标准输出流有两种:PrintWriter以及PrintStream。
这里只讲PrintStream,PrintStream是日常使用最多的输出流,System.out.println(),调用的其实就是PrintStream的println方法。
根据源码可知。
System是一个类,而System.out中,out是该类中的属性,并且有final static进行修饰,该属性的类型正是PrintStream。
因此日常所使用的System.out.println(),可以写作这种格式。

	 PrintStream out = System.out;
        out.println("hello,world");

而这样的输出形式,是直接打印在控制台上。如果想要打印在文件中,只需要调用System.setOut()即可改变输出路径,该方法中需要传入PrintStream对象,而PrintStream对象的构造函数,需要传入FileOutputStream对象,指明文件的路径。
注意:标准输出流并不需要关闭操作

**
 * @author cz
 * @date 2020/6/19/019
 * PrintStream:标准的字节输出流,默认输出在控制台
 **/
public class PrintStreamTest {
    public static void main(String[] args) throws FileNotFoundException {
        System.out.println("hello,world");

//返回的是PrintStream对象,且标准输出流不需要关闭
//        out是System类下 PrintStream类型的属性,final static修饰
        PrintStream out = System.out;
        out.println("hello,world");

//        可以改变输出方向吗?可以
//        标准输出流,不再指向控制台,指向data文件,
        PrintStream printStream = new PrintStream(new FileOutputStream("data1"));
//        修改输出方向,将输出方向修改到data文件
        System.setOut(printStream);
        System.out.println("hello zhangsan");
        System.out.println("hello lisi");
    }
}
简易日志实现

日志工具:

**
 * @author cz
 * @date 2020/6/19/019
 * 简易日志工具实现
 **/
public class LogUtils {
//    只需要传入,日志信息
    public static void log(String msg) throws FileNotFoundException {
//        标准输出流,输出到log.txt文件中,true,确保能连续写入
        PrintStream printStream = new PrintStream(new FileOutputStream("log.txt",true));
//        改变输出方向,有控制台方向改变为log文件
        System.setOut(printStream);
//        格式化时间
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        String nowTime = simpleDateFormat.format(date);

//        打印输出
        System.out.println(nowTime+": "+msg);

    }
}

日志测试:

public class LogTest {
    public static void main(String[] args) throws FileNotFoundException {
//        静态方法,不需要创建新的对象,直接调用方法即可
        LogUtils.log("用户登录");
        LogUtils.log("用户修改密码");
        LogUtils.log("用户退出");

    }
}

运行后就能在log文件中持续写入。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值