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文件中持续写入。