Java——PrintStream

利用PrintStream重新确定输出方向以记录日志

//实现功能:在日志文件中记录调用m1方法的开始时间和m1方法的结束时间
public class Hello {
	public static void main(String[] args) throws Exception{
		System.out.println("Hello World!");
		
		PrintStream printStream=System.out;
		printStream.println("Hello World");
		
		System.setOut(new PrintStream(new FileOutputStream("G:\\log.txt")));
		System.out.println("my log");
		
		SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
		System.out.println("m1方法的开始时间为:"+simpleDateFormat.format(new Date()));
		m1();
		System.out.println("m1方法的结束时间为:"+simpleDateFormat.format(new Date()));
	}
	
	public static void m1(){
		System.out.println("正在执行m1方法");
	}
}

控制台输出:
在这里插入图片描述
日志文件:
Java——PrintStream_第1张图片

你可能感兴趣的:(java)